<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户订单模型
 * @author www.dingwei.cn
 */

class ConsumerOrderModel extends MY_Model{

	public $tbOrder = 'consumer_order';
	public $tbUser = 'consumer';
	public $tbProductVariant = 'product_variant';//标签属性组合
    public $tbProductCustomCategory = 'product_custom_category';//自定义分类
	public $tbOrderProduct = 'consumer_order_product';
	public $tbProduct = 'product';
	public $tbOrderService = 'consumer_order_service'; //产品售后
    public $tbOrderLog = 'consumer_order_log';

    // 商城状态
	public $STATUS = array(
		''=>'全部',
        '1'=>'待支付',// 取消/支付
        '2'=>'待受理',// 商家接单/商家拒绝/申请售后
        '3'=>'配送中',// 申请售后
        '4'=>'待评价',// 立即评价/申请售后
        '5'=>'已完成',
        '6'=>'售后订单',
        '7'=>'交易关闭',
        '8'=>'交易关闭',
    );
    // 订单提示
    public $TIPS = array(
        '1'=>'逾期未支付，订单将自动取消',
        '2'=>'',
        '3'=>'',
        '4'=>'',
        '5'=>'',
        '6'=>'',
        '7'=>'支付超时/用户取消，订单已自动关闭',
        '8'=>'用户取消，订单已自动关闭'
    );
    // 到店状态
	public $STORE_STATUS = array(
        '1'=>'待支付',
		'2'=>'',
        '3'=>'待核销',
        '4'=>'待评价',
        '5'=>'已完成',
        '6'=>'交易关闭',
        '7'=>'交易关闭',
        '8'=>'交易关闭',
    );

    // 到店订单提示
    public $STORE_TIPS = array(
        '1'=>'逾期未支付，订单将自动取消',
        '2'=>'',
        '3'=>'等待顾客扫码核销',
        '4'=>'等待顾客评价',
        '5'=>'',
        '6'=>'',
        '7'=>'支付超时/用户取消，订单已自动关闭',
        '8'=>'用户取消，订单已自动关闭',
    );

	// 支付方式
	public $PAY_TYPE = array(
        '0'=>'暂无支付',
        '1'=>"余额支付",
        '2'=>"微信支付",
        '3'=>"支付宝",
	);

	public $EXPENSE_TYPE = array(
					'1'=>"送货上门",
					'2'=>"到店自取",
	);

	// 售后状态
	public $SERVICE_TYPE = array(
					'4'=>"售后拒绝",
					'2'=>"售后完成",
					'3'=>"售后中",
	);

	// 操作订单记录人员
    public $ORDER_LOG_TYPE = array(
        '1'=>'管理员',
        '2'=>'消费者',
        '3'=>'商户',
        '4'=>'配送员',
    );

	function __construct(){
		parent::__construct();
	}

	/////////////////////////////////////////////////
	//+----------------------------------------------
	//|	商品订单
	//+----------------------------------------------


	public function appGetInfo($orderId, $consumerId = 0,$merchantId = 0,$verificationCode = '', $port = ''){
		if ( ! $orderId && !$verificationCode){
			return array();
		}

		if ($consumerId){
			$this->db->where('o.consumer_id',$consumerId);
		}

		if ($merchantId){
			$this->db->where('o.merchant_id',$merchantId);
		}

		if ($verificationCode){
			$this->db->where('o.verification_code',$verificationCode);
		}

		if ($orderId){
			$this->db->where('o.id',$orderId);
		}

		get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
		get_instance()->loadModel('MerchantUserModel', 'mMMuser', 'merchant');

		$this->db
		->select('o.id,o.code,o.shortage_handing,o.verification_code,o.verification_bar_code,o.addtime,o.status,o.expense_type,o.shipping_type,
				o.pay_type,o.contacts,o.product_amount,o.total_amount,o.change_amount,o.gender,o.mobile,o.address,o.reality_amount,o.param,o.pay_time,
				,s.shop_name,m.mobile as merchant_mobile,s.latitude,s.longitude,m.portrait as shop_icon,
				s.province,s.city,s.county,s.address as s_address,s.street,o.shipping_fee,o.remark,o.after_sale,
				os.status as service_status,o.merchant_income,o.merchant_id,o.percent,o.expect_arrive_time,o.confirmtime')
		->join($this->tbUser.' c','c.id = o.consumer_id')
		->join($this->tbOrderService.' os','os.order_id = o.id', 'left')
		->join($this->mMMuser->tbUser.' m','m.id = o.merchant_id')
		->join($this->mMMuser->tbShop.' s', 'o.merchant_id = s.merchant_id')
        ->order_by('o.id desc,os.id desc');

		$tA = $this->getOne($this->tbOrder.' o');
		if ( ! $tA){
			return array();
		}

		$tAddress = $this->mSett->getLocationNameByIds([$tA['province'],$tA['city'],$tA['county']]);

		//二维码地址
		$tA['verification_bar_code'] = $tA['expense_type'] == 2? getImage($tA['verification_bar_code'],'og'):'';
		$tA['verification_code'] = $tA['expense_type'] == 2? $tA['verification_code']:'';
		//状态说明
		$tA['time_expire'] = 0;
		$time_expire = ($tA['addtime'] + getCustomConfig('order_expire') * 60) - time();
		if($time_expire > 0){
			$tA['time_expire'] = (string)ceil($time_expire);
		}elseif ($time_expire <= 0 && in_array($tA['status'],array(1))){
			//订单状态为待支付 时，才失效
			$tA['status'] = 7;//通用失效订单
		}
		if ($tA['expense_type'] == 1){
			$tA['status_desc'] = $this->STATUS[$tA['status']];
			if($port == 'consumer' && $tA['status'] == 2){
                $tA['status_desc'] = '备货中';
            }
		}elseif ($tA['expense_type'] == 2){
			$tA['status_desc'] = $this->STORE_STATUS[$tA['status']];
		}
        //接单倒计时
        $tA['expect_take_time'] = 0;
        if($tA['status'] == 2){
            $tA['expect_take_time'] = ((int)$tA['pay_time'] + (int)getCustomConfig('expect_take_time')*60 - time());//接单有效时间
        }

		//平台配置的售后时间
        $aftersale_limite_day = $this->mSett->get('aftersale_limite_day');
		//售后状态
        $tA['after_sale'] = empty($tA['after_sale'])?"1":$tA['after_sale'];//售后状态
        if (! empty($tA['service_status'])){
            $tA['after_sale'] = $tA['service_status'];

        }

        //是否已过售后时间
        if($tA['status'] == 4 && ($tA['confirmtime'] + $aftersale_limite_day*3600) < time()){
            $tA['after_sale'] = 2;
        }

		//商品图标
		$tA['shop_icon'] = getImage($tA['shop_icon'],'xs');

		//缺货处理解析
		$tA['shortage_handing'] = json_decode($tA['shortage_handing'],true);
        $tA['tips'] = $tA['expense_type'] == 1 ?$this->TIPS[$tA['status']]:$this->STORE_TIPS[$tA['status']];
		//地址
		$tA['shop_address'] = $tAddress[$tA['province']]['name'].
		$tAddress[$tA['city']]['name'].
		$tAddress[$tA['county']]['name'].
		$tA['s_address'].$tA['street'];
        $tA['confirmtime'] = !empty($tA['confirmtime']) ? date('m-d H:i',$tA['confirmtime']) : '';
		$tA['delivery'] = array(
				'contacts'=>$tA['contacts'],
				'mobile'=>$tA['mobile'],
				'gender'=>$tA['gender'] == 1?'先生':'女士',
				'address'=>$tA['address'],
				'shipping_type'=>$tA['shipping_type'],
				'arrivetime'=> $tA['confirmtime']?$tA['confirmtime']:'(预计)'.date('m-d H:i',$tA['expect_arrive_time']),//修改为实际送达时间
				'delivery_name'=>'',
				'delivery_mobile'=>'',
				'delivery_service'=>'',
				'delivery_status'=>'',
		);

		$tA['order'] = array(
				'code'=>$tA['code'],
				'addtime'=>date('Y-m-d H:i:s',$tA['addtime']),
				'pay_type'=>$this->PAY_TYPE[$tA['pay_type']],
		);


		$tParam = json_decode($tA['param'],true);
		$tA['param'] = array();
		$_p = [
				'coupon'=>'代金劵',
				'bonus'=>'红包',
				'full_cut'=>'满减',
				'first_order_reduce'=>'首单减免',
                'lunch_box_fee'=>'打包费',
                'postal_card'=>'包邮卡',
		];

		//处理优惠【动态】
		$tA['param']['active'] = array();
		foreach ($tParam as $k=>$v){
			if ($v){
                $value = '￥'.sprintf("%.2f", $v);
			    if ($k != 'lunch_box_fee'){
                    $value = '-'.$value;
                }
				$tA['param']['active'][] = array('key'=>$_p[$k],'value'=>$value);
			}
		}

		$tA['param']['reality_amount'] = sprintf('%.2f', $tA['reality_amount']);


		unset($tA['addtime']);
		unset($tA['pay_type']);
		unset($tA['contacts']);
		unset($tA['gender']);
		unset($tA['mobile']);
		unset($tA['address']);
		unset($tA['reality_amount']);
		unset($tA['province']);
		unset($tA['city']);
		unset($tA['county']);
		unset($tA['s_address']);
		unset($tA['street']);
		unset($tA['express_param']);
		return $tA;
	}

	/**
	 * 获取订单详情
	 * @param integer   $orderId 订单id
	 * @param int       $consumerId
	 * @param int       $merchantId
	 * @param bool      $mini
     * @param string $verificationCode   核销码
	 * @return array|array
	 * @author zyl
	 */

	public function getInfo($orderId, $consumerId = 0, $merchantId = 0, $mini = false, $verificationCode = ''){

		if ( ! $orderId && !$verificationCode){
			return array();
		}

		if ($consumerId){
			$this->db->where('o.consumer_id',$consumerId);
		}

		if ($merchantId){
			$this->db->where('o.merchant_id',$merchantId);
		}

        if ($verificationCode){
            $this->db->where('o.verification_code',$verificationCode);
        }

        if ($orderId){
            $this->db->where('o.id',$orderId);
        }
        get_instance()->loadModel('MerchantUserModel', 'mMMuser', 'merchant');

        $select = 'o.id,o.merchant_id,o.consumer_id,o.code,o.pay_code,o.percent,o.status,o.wx_type,o.expense_type,o.shipping_type,
                    o.product_amount,o.total_amount,o.pay_type,o.wx_type,o.reality_amount,o.param,o.addtime,o.remark,
                    o.merchant_take_time,o.merchant_income,o.bonus,o.last_push_time,o.change_amount,o.merchant_day_index,o.postal_card,';
		if($mini){
            $select .= 'o.pay_code,o.type,o.express_param,u.jpush_code,u.parent_id,o.is_comment,mu.jpush_code as merchant_jpush_code,
                        mu.min_order_web_amount,o.shipping_fee';

			$this->db->select($select)
                    ->join($this->tbUser.' u', 'u.id = o.consumer_id')
                    ->join($this->mMMuser->tbUser.' mu', 'mu.id = o.merchant_id');
			$tA = $this->getOne($this->tbOrder.' o');
			if ( ! $tA){
				return array();
			}

			$tA['param'] = json_decode($tA['param'],true);
			$tA['addtime'] = dateFormat($tA['addtime'], true);
			$tA['pay_type_str'] = $this->payType($tA['pay_type']);
			//unset($tA['param']);
			return $tA;
		}

		get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
		$select .= 'o.after_sale,o.pay_time,o.expect_arrive_time,o.verification_code,o.verification_bar_code,o.shipping_fee,o.province_id,o.city_id,
		            o.county_id,o.longitude,o.latitude,o.address,o.contacts,o.mobile,s.shop_name as merchant,
		                   mu.portrait,mu.mobile as merchant_mobile,mu.store_tel,mu.jpush_code as merchant_jpush_code,u.nickname as consumer,
		                   u.jpush_code,u.mobile as consumer_mobile,s.province as shop_province,s.city as shop_city,
		                   s.county as shop_county,u.portrait as consumer_portrait, s.longitude as shop_longitude,
		                   s.latitude as shop_latitude,s.address as shop_address,o.shortage_handing';
		$this->db->select($select)
						->join($this->mMMuser->tbUser.' mu', 'mu.id = o.merchant_id')
                        ->join($this->mMMuser->tbShop.' s', 's.merchant_id = mu.id')
						->join($this->tbUser.' u', 'u.id = o.consumer_id', 'left');

		$data = $this->getOne($this->tbOrder.' o');

        if($data){
            $data['param'] = $data['param']?json_decode($data['param'], true):array();
            $data['express_param'] = array();
            $data['expense_type_str'] = $this->expenseType($data['expense_type']);
            $data['pay_type_str'] = $this->payType($data['pay_type']);
            $data['tips'] = $data['expense_type'] == 1 ?$this->TIPS[$data['status']]:$this->STORE_TIPS[$data['status']];
            //订单状态 当为1 时 过期更改为7
            $time_expire = ((int)$data['addtime'] + (int)getCustomConfig('order_expire') * 60) - time();
            if ($time_expire <= 0 && $data['status'] == 1){
                //订单状态为待支付 时，才失效
                $data['status'] = 7;//通用失效订单
            }

            if ($data['expense_type'] == 2){
                $data['status_format_str'] = $this->storeStatus($data['status'], true);
                $data['status_str'] = $this->storeStatus($data['status']);
            }else{
                $data['status_format_str'] = $this->status($data['status'], true);
                $data['status_str'] = $this->status($data['status']);
            }

            //接单有效时间
            $data['expect_take_time'] = ((int)$data['pay_time'] + (int)getCustomConfig('expect_take_time')*60).'';
            $data['web_service_amount'] = $data['percent']? ($data['percent']*$data['product_amount']/100):0;//平台服务费
            $data['shipping_fee'] = $data['shipping_fee']? $data['shipping_fee']:'0';//配送费
            $data['store_tel'] = $data['store_tel']? $data['store_tel']:$data['merchant_mobile'];
            $data['consumer'] = $data['consumer']? $data['consumer']:'';
            $data['consumer_mobile'] = $data['consumer_mobile']? $data['consumer_mobile']:'';
            $data['shortage_handing'] = $data['shortage_handing']?$data['shortage_handing']:'';
            $data['verification_code'] = $data['verification_code']?$data['verification_code']:'';
            $data['verification_bar_code'] = $data['verification_bar_code']?getImage($data['verification_bar_code'],'sm'):'';
            $data['portrait'] = $data['portrait']?getImage($data['portrait'],'og'):'';
            $data['consumer_portrait'] = $data['consumer_portrait']?getImage($data['consumer_portrait'],'og'):getDefaultPortrait(0);
            $data['pay_time'] = $data['pay_time'] ? dateFormat($data['pay_time'], true) : '';
            $data['addtime'] = dateFormat($data['addtime'], true);
            $data['expect_arrive_time'] = date('m-d H:i:s',$data['expect_arrive_time']);
            $tA = $this->mSett->getLocationNameByIds([$data['province_id'],$data['city_id'],$data['county_id']]);
            $data['province'] = isset($tA[$data['province_id']]) ? $tA[$data['province_id']]['name'] : '';
            $data['city'] = isset($tA[$data['city_id']]) ? $tA[$data['city_id']]['name'] : '';
            $data['county'] = isset($tA[$data['county_id']]) ? $tA[$data['county_id']]['name'] : '';
            $data['address_all'] = ($data['province'] == $data['city'] ? $data['province'] : '')
                .$data['city'].$data['county'].$data['address'];
            //缺货处理
            $shortage = (object)array();
            if($data['shortage_handing']){
                $shortage = json_decode($data['shortage_handing'], true);
                if(!isset($shortage['value'])){
                    $shortage['value'] = 0;
                }
                $shortage['value'] = $this->getShortage($shortage['value']);
            }

            $data['shortage_handing'] = $shortage;

        }

		return $data;
	}

    /**
     * 获取订单信息抛送给配送端
     * @param $orderId  订单id
     * @param int $merchantId  商家id
     * @return array
     */
	public function getInfoForDeliveryman($orderId, $merchantId = 0){

	    if(!$orderId)return array();

        if ($merchantId){
            $this->db->where('o.merchant_id',$merchantId);
        }
        get_instance()->loadModel('MerchantUserModel', 'mMMuser', 'merchant');
        get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');

        $this->db->select('o.id,o.code,o.consumer_id,o.merchant_id,s.shop_name as merchant,mu.mobile as merchant_mobile,mu.store_tel,o.consumer_id,
				u.mobile as consumer_mobile,o.status,o.expense_type,o.remark,o.province_id,o.city_id,o.county_id,o.address,o.contacts,
				o.mobile,o.longitude,o.latitude,s.province,s.city,s.county,s.longitude as shop_longitude,o.expect_arrive_time,o.shipping_type,
				s.latitude as shop_latitude,s.street,s.address as shop_address,u.jpush_code,o.deliveryman_income,o.addtime,o.reality_amount')
            ->join($this->mMMuser->tbUser.' mu', 'mu.id = o.merchant_id')
            ->join($this->mMMuser->tbShop.' s', 's.merchant_id = mu.id')
            ->join($this->tbUser.' u', 'u.id = o.consumer_id')
            ->where('o.id', $orderId);

        $data = $this->getOne($this->tbOrder.' o');
        $data['store_tel'] = $data['store_tel']? $data['store_tel']:$data['merchant_mobile'];
        $tA = $this->mSett->getLocationNameByIds([$data['province_id'],$data['city_id'],$data['county_id']]);
        $data['provinceName'] = isset($tA[$data['province']]) ? $tA[$data['province']]['name'] : '';
        $data['cityName'] = isset($tA[$data['city']]) ? $tA[$data['city']]['name'] : '';
        $data['countyName'] = isset($tA[$data['county']]) ? $tA[$data['county']]['name'] : '';
        $data['address'] = ($data['provinceName'] == $data['cityName'] ? $data['provinceName'] : '')
            .$data['cityName'].$data['countyName'].$data['address'];
//        unset($data['shop_address']);
        $data['addtime'] = dateFormat($data['addtime'], true);
        return $data;
    }
	/**
	 * 通过"支付订单"号获取订单信息
	 * @param string $payCode 支付订单号
	 * @param number $consumerId
	 * @return array|array
	 * @author zyl
	 */
	public function getInfoByPayCode($payCode, $consumerId = 0){
		if( ! $payCode && ! $consumerId)return array();

		if ($consumerId){
			$this->db->where('consumer_id',$consumerId);
		}

		$this->db->select('id,status,shipping_type,expense_type,consumer_id,merchant_id,
		                reality_amount,latitude,longitude,expect_arrive_time')
		->where(array('pay_code' => $payCode));

		return $this->getAll($this->tbOrder.' o');
	}

    /**
     * 获取缺货处理
     * @return array
     */
    public function getShortage($key = 0){
        $config = [
            '其他商品继续配送(缺货商品退款)',//退款商品线下处理
            '缺货时电话与我沟通',
        ];

        $tData = [];

        foreach ($config as $k=>$v){
            $tName = 's'.($k+1);
            $choose = 1;
            if($key && ($key == $tName)){
                $choose = 2;
            }
            $tData[] = [
                'value'=>$tName,
                'choose'=> $choose ,
                'label'=>$v,
            ];
        }

        return $tData;
    }

    /**
     * 通过订单号获取订单信息
     * @param $code      订单号
     * @param $merchantId  商家id
     * @param $consumerId  消费者id  [consumer/product/orderPay调用] zyl
     * @return array
     */
	public function getInfoByCode($code, $merchantId = 0,$consumerId = 0){
		if( ! $code || (! $merchantId && ! $consumerId))return array();

		if ($consumerId){
			$this->db->where('o.consumer_id',$consumerId);
		}

		if ($merchantId){
			$this->db->where('o.merchant_id',$merchantId);
		}

	    $this->db->select('o.id,o.code,o.product_amount,o.total_amount,o.reality_amount,status')
                ->where(array('o.code' => $code));

        return $this->getOne($this->tbOrder.' o');
    }
	/**
	 * 获取订单id 通过codes
	 * @param array $codes 订单号数组 [下单时需要用到]
	 * @return array|array
	 * @author zyl
	 */
	public function getOrderByCodes($codes){
		if ( ! $codes){
			return array();
		}

		$this->db->select('id,merchant_id,consumer_id')
		->where_in('code',$codes);
		$tA = $this->getAll($this->tbOrder);

		$tData = array();
		foreach ($tA as $k=>$v){
			$tData[$v['merchant_id']] = $v['id'];
		}
		return $tData;
	}

	/**
	 * 获取订单id 通过codes
	 * @param array $codes 订单号数组 [下单时需要用到]
	 * @return array|array
	 * @author zyl
	 */
	public function getInfoByCodes($codes){
		if ( ! $codes){
			return array();
		}

		$this->db->select('id,merchant_id,consumer_id,reality_amount,code,status')
		->where_in('code',$codes);
		$tA = $this->getAll($this->tbOrder);

		$tData = array();
		foreach ($tA as $k=>$v){
			$tData[$v['code']] = $v;
		}
		return $tData;
	}

	/**
	 * 获取订单产品信息
	 * @param integer $orderId 订单id
     * @param int       $consumerId
     * @param int       $merchantId
	 * @return array
	 * @author zyl
	 */
	public function getOrderProductList($orderId, $consumerId = 0, $merchantId = 0){
		if ( ! $orderId){
			return array();
		}

		if($consumerId){
		    $this->db->where('o.consumer_id', $consumerId);
        }

        if($merchantId){
            $this->db->where('o.merchant_id', $merchantId);
        }

		$this->db->select('op.id as order_product_id,op.reality_amount,c.cat_name,p.icon,op.product_id,op.price,op.quantity,
		                    op.tags,p.name,p.weight,p.sale_quantity,v.sale_quantity as v_sale_quantity,v.property,op.variant_id')
            ->join($this->tbOrder.' o', 'o.id = op.order_id')
            ->join($this->tbProduct.' p', 'p.id = op.product_id')
            ->join($this->tbProductCustomCategory.' c', 'c.id = p.category_id')
            ->join($this->tbProductVariant.' v', 'v.product_id = op.product_id and v.sort = op.variant_id', 'left')
		    ->where('op.order_id',$orderId)
            ->order_by('op.id desc');

		$tA = $this->getAll($this->tbOrderProduct.' op');

		if ( ! $tA){
			return array();
		}

		$aData = array();
		foreach ($tA as $k=>$v){
		    $v['name'] = $v['cat_name'] ? $v['cat_name'].':'.$v['name'] : $v['name'];
            $v['property_new'] = $v['property']? '('.implode(',',json_decode($v['property'], true)).')':'';
            $v['property'] = $v['property']? '规格:'. implode(',',json_decode($v['property'], true)):'';
            $tags = $v['tags']? ' 属性:'. $v['tags']:'';
            $v['property'] .= $tags;
            $v['icon'] = getImage($v['icon'],'xs');
            $aData[] = $v;
		}

		return $aData;
	}

	/**
	 * 保存消费者订单
	 * @param array $data 数据
	 * @param int $code 订单号
	 * @param int $id
	 * @param int $payCode      支付订单号
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function save($data,$code = 0, $id = 0,$payCode = 0){
		if ($code || $id || $payCode){
            if ($code){
                $this->db->where('code',$code);
            }

			if ($id){
                $this->db->where('id',$id);
            }

            if ($payCode){
            	$this->db->where('pay_code',$payCode);
            }
			$query = $this->update($this->tbOrder, $data);
			return $query === false ? false : true;
		}else{
			return $this->insert($this->tbOrder, $data);
		}
	}

	/**
	 * 保存消费者订单
	 * @param array $data 数据
	 * @param number $payCode 预支付订单号
	 * @param number $code 订单号
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function saveBatch($data,$payCode = 0,$code = array(), $key =''){
	    if(!$data) return false;
		if ($code){
			$this->db->where_in('code',$code);
			$query = $this->update($this->tbOrder, $data);
			return $query === false ? false : true;
		}elseif ($payCode){
			$this->db->where('pay_code',$payCode);
			$query = $this->updateBatch($this->tbOrder, $data);
			return $query === false ? false : true;
		}elseif ($key == 'id'){
            return $this->updateBatch($this->tbOrder, $data, 'id');
        }
		else{
			return $this->insertBatch($this->tbOrder, $data);
		}
	}

	/**
	 * 保存消费者订单
	 * @param array $data   数据
	 * @param int   $id     商品详情id
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function saveOrderProduct($data, $id = 0){
		if ( ! $data){
			return 0;
		}
		if ($id){
            $this->db->where('id',$id);
            return $this->update($this->tbOrderProduct, $data);
        }
		return $this->insertBatch($this->tbOrderProduct, $data);
	}

	/**
	 * 更改订单状态 待评价->完成
	 * @param unknown $orderId
	 * @return boolean
	 */
	public function saveOrderStatus($orderId){

		$this->db->where('order_id',$orderId);
		$this->db->where('is_comment',1);

		if ($this->getOne($this->tbOrderProduct)){
			return true;
		}

		if ( ! $this->save(array('status'=>5),0,$orderId)){
			return false;
		}
		return true;
	}

	/**
	 * 获取订单商品信息
	 * @param int $id		订单商品id
	 * @param int $orderId	订单id
	 * @return array
	 * @author zyl
	 */
	public function getOrderProductInfo($id = 0, $orderId = 0){

		if ( ! $id && ! $orderId){
			return array();
		}

		$this->db->select('*');
		if ($id){
			$this->db->where('id',$id);
		}

		if ($orderId){
			$this->db->where('order_id',$orderId);
		}

		$data = $this->getOne($this->tbOrderProduct);
		if ( ! $data){
			return array();
		}

        $data['total'] = ceil($data['price']*$data['quantity']); // 商品总金额
        $data['refound_amount'] = $data['merchant_refound'] + $data['web_refound']; // 退款金额
        return $data;
	}

	/**
	 * 获取订单商品信息
	 * @param array $ids
	 * @param array $orderIds	订单商品ids
	 * @param int   $afterSale	是否申请售后(1未申请  2已申请)[heyu]
	 * @param bool  $mini                  [heyu]
	 * @return array
	 * @author zyl
	 */
	public function getOrderProductInfoByIds($ids= array(),$orderIds = array(), $afterSale = 0, $mini =false, $merchant = false){

		if ( ! $ids && ! $orderIds){
			return array();
		}
		if (!empty($ids)){
		    if (is_array($ids)){
                $this->db->where_in('op.id',$ids);
            }else{
                $this->db->where('op.id',$ids);
            }
		}

		if (!empty($orderIds)){
            if (is_array($orderIds)) {
                $this->db->where_in('op.order_id', $orderIds);
            }else{
                $this->db->where('op.order_id', $orderIds);
            }
		}

		if ($afterSale){
		    $this->db->where(array('op.after_sale' => $afterSale));
        }

        if ($mini){
            $this->db->select('op.id,op.order_id,op.product_id,op.price,op.variant_id,op.quantity,op.reality_amount');
            $tA = $this->getAll($this->tbOrderProduct.' op');
            $tData = array();
            foreach ($tA as $k=>&$v){
                $tData[$v['id']]= $v;
            }
            return $tData;
        }

        $select = 'op.id,op.order_id,op.product_id,op.price,op.variant_id,op.quantity,
        op.reality_amount,v.property,p.name,p.is_limited as product_is_limited,p.quantity as product_quantity,
        v.quantity as variant_quantity,v.is_limited as variant_is_limited,os.status';

		$this->db->join($this->tbProductVariant.' v','v.product_id = op.product_id and v.sort = op.variant_id', 'left')
            ->join($this->tbOrderService.' os','os.order_product_id = op.id ','left')//售后订单 左连接
            ->join($this->tbProduct.' p','op.product_id = p.id');

        if($merchant){
            get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
            //获取商户信息
            $select .= ',mu.id as merchant_id,mu.jpush_code';
            $this->db->join($this->mMerchant->tbUser.' mu','mu.id = p.merchant_id');
        }
        $this->db->select($select);
		$tA = $this->getAll($this->tbOrderProduct.' op');

		$tData = array();
		foreach ($tA as $k=>&$v){
            $v['status'] = $v['status'] ? $this->SERVICE_TYPE[$v['status']]:'未申请';
		    if (isset($v['property'])) {
                $v['property'] = implode('/', json_decode($v['property'], true));
            }
			if (!empty($ids)){
				$tData[$v['id']] = $v;
			}elseif (!empty($orderIds)){
				$tData[$v['order_id']][] = $v;
			}
		}

		return $tData;
	}

    /**
     * 获取商城状态
     * @param int       $key
     * @param bool      $show
     * @param bool|int  $isButtons    获取对应操作按钮
     * @param bool      $jurisdiction true： 验证权限  false： 不验证权限
     * @return array|mixed|string
     */
	public function status($key = null, $show = false, $isButtons = false, $jurisdiction = true){

		if($key === null){
            $status = $this->STATUS;
            $status[3] = $status[3].'(待核销)';
            $status[7] = $status[7].'(未支付)';
            $status[8] = $status[8].'(用户取消)';
//            unset($status[7]);
			return $status;
		}

		if($key !== null && ! isset($this->STATUS[$key])){
			return '';
		}

		if( ! $show && !$isButtons){
			return $this->STATUS[$key];
		}

		if ($show) {
            if ($key == 1) {
                return '<span class="label badge-success">' . $this->STATUS[$key] . '</span>';
            } else if ($key == 2) {
                return '<span class="label label-warning">' . $this->STATUS[$key] . '</span>';
            } else if ($key == 3) {
                return '<span class="label label-warning">' . $this->STATUS[$key] . '</span>';
            } else if ($key == 4) {
                return '<span class="label label-info">' . $this->STATUS[$key] . '</span>';
            } else if ($key == 5) {
                return '<span class="label label-info">' . $this->STATUS[$key] . '</span>';
            } else if ($key == 6 ) {
                return '<span class="label label-default">' . $this->STATUS[$key] . '</span>';
            }else if ($key == 7 ) {
                return '<span class="label label-default">' . $this->STATUS[$key] . '(未支付)</span>';
            }else if ($key == 8 ) {
                return '<span class="label label-default">' . $this->STATUS[$key] . '(用户取消)</span>';
            }
        }
		if ($isButtons){
            $a = array();
            $order = array();
            switch ($key){
                case 1:
                    $order = array(
                        'label' => '取消订单',
                        'attr' => array(
                            'href' => getUrl('order/home/cancelOrder'),
                            'class' => 'btn btn-sm yellow-stripe default ajax-order-btn',
                            'alert-message' => '是否确认取消订单？'
                        ),
                        'tag' => 'a',
                    );
                    if ($jurisdiction){
                        $order['permissions'] = array(
                            'module' => 'order',
                            'key' => 'home-cancel'
                        );
                    }
                    $a['order'] = adminCreateBtn($order);
                    break;
                case  2:
                    $order[] = array(
                        'label' => '接单',
                        'attr' => array(
                            'href' => getUrl('order/home/accept'),
                            'class' => 'btn btn-sm blue-stripe default ajax-order-btn',
                            'alert-message' => '是否确认接单？'
                        ),
                        'tag' => 'a',
                    );
//                    $order[] = array(
//                        'label' => '拒绝接单',
//                        'attr' => array(
//                            'href' => getUrl('order/home/refuse'),
//                            'class' => 'btn btn-sm red-stripe default ajax-order-btn',
//                            'alert-message' => '是否确认拒绝接单？'
//                        ),
//                        'tag' => 'a',
//                    );
                    $order[] = array(
                        'label' => '申请售后',
                        'attr' => array(
                            'href' => 'javascript:;',
                            'class' => 'btn btn-sm yellow-stripe default customer-service',
                        ),
                        'tag' => 'a',
                    );
                    if ($jurisdiction){
                        $order[0]['permissions'] = array(
                            'module' => 'order',
                            'key' => 'home-accept'
                        );
                        $order[1]['permissions'] = array(
                            'module' => 'order',
                            'key' => 'home-service'
                        );
                    }
                    $a['order'] = adminCreateBtn($order[0]);
                    $a['order'] .= '&nbsp;&nbsp;&nbsp;'.adminCreateBtn($order[1]);
                    break;
                case  3:
                    $order[] = array(
                        'label' => '确认收货',
                        'attr' => array(
                            'href' => getUrl('order/home/confirmReceipt'),
                            'class' => 'btn btn-sm blue-stripe default ajax-order-btn',
                            'alert-message' => '是否确认收货？'
                        ),
                        'tag' => 'a',
                    );
                    $order[] = array(
                        'label' => '申请售后',
                        'attr' => array(
                            'href' => 'javascript:;',
                            'class' => 'btn btn-sm yellow-stripe default customer-service',
                        ),
                        'tag' => 'a',
                    );
                    if ($jurisdiction){
                        $order[0]['permissions'] = array(
                            'module' => 'order',
                            'key' => 'home-confirm'
                        );
                        $order[1]['permissions'] = array(
                            'module' => 'order',
                            'key' => 'home-service'
                        );
                    }
                    $a['order'] = adminCreateBtn($order[0]);
                    $a['order'] .= '&nbsp;&nbsp;&nbsp;'.adminCreateBtn($order[1]);
                    break;
                case  4:
                    $order = array(
                        'label' => '申请售后',
                        'attr' => array(
                            'href' => 'javascript:;',
                            'class' => 'btn btn-sm yellow-stripe default customer-service',
                        ),
                        'tag' => 'a',
                    );
                    if ($jurisdiction){
                        $order['permissions'] = array(
                            'module' => 'order',
                            'key' => 'home-service'
                        );
                    }
                    $a['order'] = adminCreateBtn($order);
                    break;
                case  7:
                    $order = array(
                        'label' => '删除',
                        'attr' => array(
                            'href' => getUrl('order/home/deleteOrder'),
                            'class' => 'btn btn-sm red-stripe default ajax-order-btn',
                            'alert-message' => '是否确认删除订单？'
                        ),
                        'tag' => 'a',
                    );
                    if ($jurisdiction){
                        $order['permissions'] = array(
                            'module' => 'order',
                            'key' => 'home-delete'
                        );
                    }
                    $a['order'] = adminCreateBtn($order);
                    break;
            }
            return $a;
        }
		return '';
	}

    /**
     * 获取到到店状态
     * @param int       $key
     * @param bool      $show
     * @param bool|int  $isButtons    获取对应操作按钮
     * @param bool      $jurisdiction
     * @return array|mixed|string
     */
    public function storeStatus($key = null, $show = false, $isButtons = false, $jurisdiction = true){

        if($key === null){
            return $this->STORE_STATUS;
        }

        if($key !== null && ! isset($this->STORE_STATUS[$key])){
            return '';
        }

        if( ! $show && !$isButtons){
            return $this->STORE_STATUS[$key];
        }

        if ($show) {
            if ($key == 1) {
                return '<span class="label badge-success">' . $this->STORE_STATUS[$key] . '</span>';
            } else if ($key == 3) {
                return '<span class="label label-warning">' . $this->STORE_STATUS[$key] . '</span>';
            } else if ($key == 4) {
                return '<span class="label label-info">' . $this->STORE_STATUS[$key] . '</span>';
            } else if ($key == 5) {
                return '<span class="label label-info">' . $this->STORE_STATUS[$key] . '</span>';
            } else if ($key == 6 ) {
                return '<span class="label label-default">' . $this->STATUS[$key] . '</span>';
            }else if ($key == 7 ) {
                return '<span class="label label-default">' . $this->STATUS[$key] . '(未支付)</span>';
            }else if ($key == 8 ) {
                return '<span class="label label-default">' . $this->STATUS[$key] . '(用户取消)</span>';
            }
        }
        if ($isButtons){
            $a = array();
            switch ($key){
                case 1:
                    $order = array(
                        'label' => '取消订单',
                        'attr' => array(
                            'href' => getUrl('order/home/cancelOrder'),
                            'class' => 'btn btn-sm yellow-stripe default ajax-order-btn',
                            'alert-message' => '是否确认取消订单？'
                        ),
                        'tag' => 'a',
                    );
                    if ($jurisdiction){
                        $order['permissions'] = array(
                            'module' => 'group',
                            'key' => 'status'
                        );
                    }
                    $a['order'] = adminCreateBtn($order);
                    break;
                case  3:
                    $order = array(
                        'label' => '立即核销',
                        'attr' => array(
                            'href' => getUrl('order/home/confirmReceipt'),
                            'class' => 'btn btn-sm blue-stripe default ajax-order-btn',
                            'alert-message' => '是否确认立即核销？'
                        ),
                        'tag' => 'a',
                    );
                    $product = array(
                        'label' => '申请售后',
                        'attr' => array(
                            'href' => 'javascript:;',
                            'class' => 'btn btn-xs yellow-stripe default customer-service',
                        ),
                        'tag' => 'a',
                    );
                    if ($jurisdiction){
                        $product['permissions'] = array(
                            'module' => 'group',
                            'key' => 'status'
                        );
                        $order['permissions'] = array(
                            'module' => 'group',
                            'key' => 'status'
                        );
                    }
                    $a['order'] = adminCreateBtn($order);
                    $a['product'] = adminCreateBtn($product);
                    break;
                case  4:
                    $product = array(
                        'label' => '申请售后',
                        'attr' => array(
                            'href' => 'javascript:;',
                            'class' => 'btn btn-xs yellow-stripe default customer-service',
                        ),
                        'tag' => 'a',
                    );
                    if ($jurisdiction){
                        $product['permissions'] = array(
                            'module' => 'group',
                            'key' => 'status'
                        );
                    }
                    $a['product'] = adminCreateBtn($product);
                    break;
                case  7:
                    $order = array(
                        'label' => '删除',
                        'attr' => array(
                            'href' => getUrl('order/home/deleteOrder'),
                            'class' => 'btn btn-sm red-stripe default ajax-order-btn',
                            'alert-message' => '是否确认删除订单？'
                        ),
                        'tag' => 'a'
                    );
                    if ($jurisdiction){
                        $order['permissions'] = array(
                            'module' => 'group',
                            'key' => 'status'
                        );
                    }
                    $a['order'] = adminCreateBtn($order);
                    break;
            }
            return $a;
        }

        return '';
    }

    /**
     * 支付类型
     * @param null $key
     * @return array|mixed|string
     */
	public function payType($key = null){

		if($key === null){
			return $this->PAY_TYPE;
		}

		return isset($this->PAY_TYPE[$key]) ? $this->PAY_TYPE[$key] : '';
	}

    /**
     * 消费类型
     * @param null $key
     * @return array|mixed|string
     */
	public function expenseType($key = null){

		if($key === null){
			return $this->EXPENSE_TYPE;
		}
		return isset($this->EXPENSE_TYPE[$key]) ? $this->EXPENSE_TYPE[$key] : '';
	}

	/**
	 * 获取订单列表
	 * @param integer $consumerId   消费者id
	 * @param int     $expenseType  消费类型
	 * @param int     $status       状态
	 * @param integer $page 分页
	 * @return array|array|array[]|number[]|unknown[]
	 * @author zyl
	 */
	public function appGetList($consumerId,$expenseType = 0, $status = 0, $page, $port = ''){

		if ( ! $consumerId ){
			return array();
		}

		if ($expenseType){
			$this->db->where('o.expense_type',$expenseType);
		}

		if ($status){
			$this->db->where('o.status',$status);
			if ($status == 1){
				//不过期的订单
				$this->db->where('o.addtime >',(time() - getCustomConfig('order_expire') * 60));
			}
		}

		if($consumerId){
		    $this->db->where('o.consumer_id', $consumerId);
        }

		$this->db
		    ->select('o.id,o.code,o.type,o.expense_type,o.reality_amount,o.pay_type,o.merchant_id,o.status,
		            o.addtime,o.shipping_type,o.pay_time,os.service_status')
            ->join('(select order_id,status as service_status from '.$this->tbOrderService.' order by addtime DESC) os','os.order_id = o.id', 'left')
                ->group_by('o.id')
            ->order_by('o.id desc');

		$this->db->where('o.is_consumer_delete <> 2 '); //2-消费者删除

		$tA = $this->appPage($this->tbOrder.' o', $page);

		if ( ! $tA['list']){
			return array();
		}

		foreach ($tA['list'] as $k=>$v){
			$tA['list'][$k]['time_expire'] = 0;
			$time_expire = ($v['addtime'] + getCustomConfig('order_expire') * 60) - time();
			if($time_expire > 0){
				$tA['list'][$k]['time_expire'] = (string)ceil($time_expire);
			}elseif ($time_expire <= 0 && in_array($v['status'],array(1))){
				//订单状态为待支付 时，才失效
				$tA['list'][$k]['status'] = 7;//通用失效订单
				$v['status'] = 7;//通用失效订单
			}

            $tA['list'][$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            if ($v['expense_type'] == 1){
				$tA['list'][$k]['status_desc'] = $this->STATUS[$v['status']];
				if($port == 'consumer' && $v['status'] == 2){
                    $tA['list'][$k]['status_desc'] = '备货中';
                }
            }elseif ($v['expense_type'] == 2){
				$tA['list'][$k]['status_desc'] = $this->STORE_STATUS[$v['status']];
            }
            //售后状态
            $tA['list'][$k]['after_sale'] = empty($v['after_sale'])?"1":$v['after_sale'];//售后状态
            $tA['list'][$k]['service_status'] = empty($v['service_status'])?"":$v['service_status'];

            if (! empty($tA['list'][$k]['service_status'])){
                $tA['list'][$k]['after_sale'] = $v['service_status'];
            }
            //接单倒计时
            $tA['list'][$k]['expect_take_time'] = 0;
            if($v['status'] == 2){
                $tA['list'][$k]['expect_take_time'] = ((int)$v['pay_time'] + (int)getCustomConfig('expect_take_time')*60 - time());//接单有效时间
            }

		}

		return $tA['list'];

	}

	/**
     * 获取商家销量
     * @param $merchantId
     */
    public function getMonthSaleCount($merchantId){
        if(!$merchantId){
            return array();
        }

        $this->db->select('merchant_id,COUNT(distinct id) as month_total')
                ->where_in('status', array(4,5))
                ->where('addtime >=', strtotime('- 30 day',time()))
                ->where_in('merchant_id',$merchantId);
        $tA = $this->getAll($this->tbOrder);

        $data = array();
        if($tA){
            foreach ($tA as $v){
                $data[$v['merchant_id']] = $v['month_total'];
            }
        }

        return $data;
    }
    /**
     * 获取商家订单列表
     * @param integer $merchantId   消费者id
     * @param int     $expenseType  消费类型
     * @param int     $status       状态
     * @param integer $page 分页
     * @param integer $time 接单时限 （分钟）
     * @return array
     * @author khj
     */
    public function appGetMerchantOrderList($merchantId,$expenseType = 0, $status = 0, $page, $mini = false)
    {

        if ( ! $merchantId ){
            return array();
        }

        if ($expenseType){
            $this->db->where('o.expense_type',$expenseType);
        }

        if ($status){
            $this->db->where('o.status',$status);
        }else{
            $this->db->where_not_in('o.status', array(7));
        }

        $this->db->where(array('o.merchant_id' => $merchantId,'o.is_merchant_delete !=' => 2));

        if($mini){//核销记录

            $this->db
                ->select('o.id,o.code,o.reality_amount,o.confirmtime')
                ->where_in('o.status', array(4,5))
                ->order_by('o.confirmtime desc');

            $tA = $this->appPage($this->tbOrder. ' o', $page);
            foreach ($tA['list'] as $k=>$v){
                $tA['list'][$k]['confirmtime'] = dateFormat($v['confirmtime'], true);
            }

            return $tA['list'];
        }

        $this->db
            ->select('o.id,o.code,o.type,o.expense_type,o.shipping_type,o.reality_amount as total_amount,o.pay_type,o.merchant_id,
                      o.status,o.addtime,p.name,p.icon,op.quantity,count(product_id) as product_count,o.pay_time')
            ->join($this->tbOrderProduct.' op', 'op.order_id = o.id')
            ->join($this->tbProduct.' p', 'p.id = op.product_id')
            ->order_by('o.addtime desc')
            ->group_by('o.id');

        $tA = $this->appPage($this->tbOrder. ' o', $page);

        if ( ! $tA['list']){
            return array();
        }

        foreach ($tA['list'] as $k=>$v){

            $tA['list'][$k]['tips'] = $v['expense_type'] == 1 ?$this->TIPS[$v['status']]:$this->STORE_TIPS[$v['status']];
            $tA['list'][$k]['addtime'] = dateFormat($v['addtime'], true);
            $tA['list'][$k]['status_desc'] = $v['expense_type'] == 1 ?$this->STATUS[$v['status']]:$this->STORE_STATUS[$v['status']];
            if($v['icon']){
                $tA['list'][$k]['icon'] = getImage($v['icon'],'xs');
            }
        }
        return $tA['list'];

    }

    /**
     * 获取商家今日订单数量
     * @param $addtime 商家接单时间
     */
    public function getMerchantOrderCount($merchantId, $addtime){
        if(!$merchantId || !$addtime){
            return '';
        }

        $today = strtotime(date('Y-m-d', $addtime));
        $this->db->where(array('merchant_id' => $merchantId))
                ->where_not_in('status', array(1,7,8))
//                ->where_in('status', array(3,4,5))
                 ->where('merchant_take_time>'.$today.' AND merchant_take_time<='.$addtime);
        $count = $this->count($this->tbOrder);

        return $count;
    }

    /**
     * 核销记录统计
     * @param $merchantId   商户id
     * * @param string $start  开始时间
     * @param string $end    结束时间
     * @return array
     */
    public function merchantCheckOrderStatistical($merchantId,$start = '', $end = ''){
        if(!$merchantId)return array();
        $this->db
            ->select('count(if(confirmtime >= '.$start.' and confirmtime < '.$end.', id, null)) as total,
                    sum(if(confirmtime >= '.$start.' and confirmtime < '.$end.', reality_amount, null)) as amount')
            ->where_in('status', array(4,5))
            ->where('merchant_id', $merchantId)
            ->where('expense_type', 2)
            ->order_by('confirmtime desc');

        return $this->getOne($this->tbOrder);
    }

    /**
     * 删除订单
     * @param $id
     * @return bool
     * @author heyu
     */
    public function deleteOrder($id){
        if (!$id){
            return false;
        }
        $this->db->where(array('id' => $id));
        return $this->delete($this->tbOrder);
    }

    /**
     * 后台获取订单
     * @param int   $merchantId
     * @param int   $consumerId
     * @param array $ci             区域
     * @param array $export         导出
     * @return array
     * @author heyu
     */
    public function adminPcGetOrderList($merchantId = 0, $consumerId = 0, $ci = array(), $export = array()){
        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $dateFrom = strtotime(get('add_time_from'));
        $dateTo = strtotime(get('add_time_to'));
        $payDateFrom = strtotime(get('pay_time_from'));
        $payDateTo = strtotime(get('pay_time_to'));
        $code = trim(get('orderCode'));
        $type = (int)get('type');
        $expenseType = (int)get('expenseType');
        $merchantDayIndex = get('merchant_day_index');
        $payType = (int)get('payType');
        $status = (int)get('orderStatus');
        $statusArr = get('statusArr');
        $payArr = get('payArr');
        $realityAmountFrom = (int)get('reality_amount_from'); // 实付金额大于等于
        $realityAmountTo = (int)get('reality_amount_to'); // 实付金额大于等于
        $amountFrom = get('amount_from'); // 订单总金额大于等于
        $amountTo = get('amount_to'); // 订单总金额小于等于
        $time = trim(get('time')); // 销售统计查看当天销售订单

        $take_time_from = strtotime(get('take_time_from'));
        $take_time_to = strtotime(get('take_time_to'));

        $discount_amount_from = get('discount_amount_from');
        $discount_amount_to = get('discount_amount_to');

        $merchant = trim(get('merchant'));
        $consumer = trim(get('consumer'));

        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        $this->db->select('o.id,o.merchant_day_index,o.code,s.shop_name as merchant,u.mobile as consumer,c.name as type,(o.bonus+o.postal_card+o.merchant_discount) as discount,
				o.status,o.addtime,o.pay_time,o.merchant_take_time,o.expense_type,o.pay_type,o.total_amount,o.status,o.reality_amount,mu.store_tel,u.nickname as consumerName,if(change_amount!=0 AND change_amount is not NULL,(total_amount - change_amount), 0) AS change_amount')
            ->join($this->mMerchant->tbUser.' mu', 'mu.id = o.merchant_id')
            ->join($this->mMerchant->tbShop.' s', 's.merchant_id = o.merchant_id')
            ->join($this->tbUser.' u', 'u.id = o.consumer_id')
            ->join($this->mMerchant->tbCat.' c', 'c.id = o.type');

        if($merchantDayIndex){
            if(strpos($merchantDayIndex, '#') !== false){
                
                $merchantDayIndex = str_replace('#','',$merchantDayIndex);
            }

            $this->db->where('o.merchant_day_index', $merchantDayIndex);
        }
        if($merchantId){
            $this->db->where('o.merchant_id', $merchantId);
        }
        if($consumerId){
            $this->db->where('o.consumer_id', $consumerId);
        }
        if (!empty($ci)){
            $this->db->where_in('s.county', $ci);
        }
        if($dateFrom){
            $this->db->where('o.addtime >=', $dateFrom);
        }
        if($dateTo){
            $this->db->where('o.addtime <=', strtotime('+1day',$dateTo));
        }
        if($payDateFrom){
            $this->db->where('o.pay_time >=', $payDateFrom);
        }
        if($payDateTo){
            $this->db->where('o.pay_time <=', $payDateTo);
        }
        if($take_time_from){
            $this->db->where('o.merchant_take_time >=', $take_time_from);
        }
        if($take_time_to){
            $this->db->where('o.merchant_take_time <', strtotime('+1day', $take_time_to));
        }
        if($code){
            $this->db->like('o.code', $code);
        }
        if($type){
            $this->db->where('o.type', $type);
        }
        if($expenseType){
            $this->db->where('o.expense_type', $expenseType);
        }
        if($payType){
            $payType -= 1;
            $this->db->where('o.pay_type', $payType);
        }
        if($status){
            $this->db->where('o.status', $status);
        }
        if($statusArr){
            if(is_array($statusArr)){
                $end = end($statusArr);
                if($end){
                    $this->db->where('o.status in ('.$end.')');
                }
            }
            if(is_string($statusArr)){
                $this->db->where('o.status in ('.$statusArr.')');
            }
        }

        if($payArr){
            if(is_array($payArr)){
                $endpay = end($payArr);
                if($endpay){
                    $this->db->where('o.pay_type in ('.$endpay.')');
                }
            }
            if(is_string($payArr)){
                $this->db->where('o.pay_type in ('.$payArr.')');
            }
        }

        if ($realityAmountFrom){
            $this->db->where('o.reality_amount >=', $realityAmountFrom);
        }
        if ($realityAmountTo){
            $this->db->where('o.reality_amount <=', $realityAmountTo);
        }
        if ($discount_amount_from){
            $this->db->where('(o.bonus+o.postal_card+o.merchant_discount) >=', $discount_amount_from);
        }
        if ($discount_amount_to){
            $this->db->where('(o.bonus+o.postal_card+o.merchant_discount) <=', $discount_amount_to);
        }
        if($amountFrom){
            $this->db->where('o.total_amount >=', $amountFrom);
        }
        if($amountTo){
            $this->db->where('o.total_amount <=', $amountTo);
        }
        if($merchant){
            $this->db->like('s.shop_name', $merchant);
        }
        if($consumer){
            $this->db->like('u.mobile', $consumer);
        }
        if ($time){
            $starTime = strtotime($time.' 00:00:00');
            $endTime = $starTime+86400;
            $this->db->where_in('o.status',array(3,4,5,6))
                ->where('(o.merchant_take_time >='.$starTime.' and o.merchant_take_time <='.$endTime.')');
        }
        if ($take_time_from or  $take_time_to){
            $this->db->where_in('o.status',array(3,4,5,6));
        }

        if ($merchantId || $consumerId){
            if ($iSortCol_0 == 3){
                $this->db->order_by('o.total_amount', $sSortDir_0); // 订单金额
            }else if($iSortCol_0 == 4){
                $this->db->order_by('o.reality_amount', $sSortDir_0); // 实付金额
            }else if($iSortCol_0 == 6){
                $this->db->order_by('o.addtime', $sSortDir_0); // 下单时间
            }else{
                $this->db->order_by('o.id desc');
            }
        }else{
            if ($iSortCol_0 == 5){
                $this->db->order_by('o.total_amount', $sSortDir_0); // 订单金额
            }else if($iSortCol_0 == 6){
                $this->db->order_by('o.reality_amount', $sSortDir_0); // 订单实付金额
            }else if($iSortCol_0 == 7){
                $this->db->order_by('o.addtime', $sSortDir_0); // 下单时间
            }else{
                $this->db->order_by('o.id desc');
            }
        }

        if (empty($export)){
            $data = $this->pagination($this->tbOrder.' o');

            return $data;
        }else{
            $tA = $this->appPage($this->tbOrder.' o', $export['page'], false, $export['pageNumber']);

            return $tA['list'];
        }
    }

    /**
     * 统计销售额
     * @param int   $time
     * @param bool  $isClosure        统计交易关闭订单总和
     * @param array $ci
     * @return array
     * @author heyu
     */
    public function getTotalOrder($time = 0, $isClosure = false, $ci = array()){
        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        if (!empty($ci)){
            $this->db->join($this->mMerchant->tbShop.' s', 'o.merchant_id=s.merchant_id')
                ->where_in('s.county', $ci);
        }
        if ($isClosure){
            $endTime = $time - 86400;
            $this->db->where('o.addtime >='.$time)
                ->where('o.addtime <'.$endTime)
                ->where_in('o.status','6,7');
            return $this->count($this->tbOrder.' o');
        }
        if ($time){
            $this->db->where('o.addtime > '.$time);
        }
        $this->db->select('sum(o.reality_amount) as total')
            ->where_in('o.status', array(4,5));
        $tA = $this->getOne($this->tbOrder.' o');
        return $tA['total'];
    }

    /**
     * 统计超3天未发货订单
     * @param bool  $isCount
     * @param array $ci
     * @return array
     * @author heyu
     */
    public function getOverThreeDaysOrderList($isCount = false, $ci = array()){
        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');

        $code = trim(get('orderCode'));
        $type = (int)get('type');
        $expenseType = (int)get('expenseType');
        $payType = (int)get('payType');
        $status = (int)get('orderStatus');
        $amountFrom = get('amount_from'); // 订单总金额大于等于
        $amountTo = get('amount_to'); // 订单总金额小于等于
        $merchant = trim(get('merchant'));
        $consumer = trim(get('consumer'));
        $dateFrom = strtotime(get('add_time_from'));
        $dateTo = strtotime(get('add_time_to'));


        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"
        $time = date('Y-m-d', time());
        $time = strtotime($time.'00:00:00')-259200; // 三天前零点时间
        if($dateFrom){
            $this->db->where('o.addtime >=', $dateFrom);
        }
        if($dateTo){
            $this->db->where('o.addtime <', strtotime('+1day', $dateTo));
        }
        if($code){
            $this->db->like('o.code', $code);
        }
        if($type){
            $this->db->where('o.type', $type);
        }
        if($expenseType){
            $this->db->where('o.expense_type', $expenseType);
        }
        if($payType){
            $this->db->where('o.pay_type', $payType);
        }
        if($status){
            $this->db->where('o.status', $status);
        }
        if($amountFrom){
            $this->db->where('o.total_amount <=', $amountFrom);
        }
        if($amountTo){
            $this->db->where('o.total_amount <=', $amountTo);
        }
        if($merchant){
            $this->db->like('s.shop_name', $merchant);
        }
        if($consumer){
            $this->db->like('u.nickname', $consumer);
        }
        if($dateFrom){
            $this->db->where('o.addtime >=', $dateFrom);
        }
        if($dateTo){
            $this->db->where('o.addtime <', strtotime('+1day', $dateTo));
        }
        if (!empty($ci)){
            $this->db->where_in('s.county', $ci);
        }
        $this->db->select('o.id,o.code,s.shop_name as merchant,u.nickname as consumer,c.name as type,
				o.status,o.addtime,o.expense_type,o.pay_type,o.total_amount,o.status,o.reality_amount')
            ->join($this->mMerchant->tbUser.' mu', 'mu.id = o.merchant_id')
            ->join($this->mMerchant->tbShop.' s', 's.merchant_id = o.merchant_id')
            ->join($this->tbUser.' u', 'u.id = o.consumer_id')
            ->join($this->mMerchant->tbCat.' c', 'c.id = o.type')
            ->where(array('o.addtime' => '<'.$time, 'o.status' => '2'));
        if ($isCount){
            return $this->count($this->tbOrder.' o');
        }
        if ($iSortCol_0 == 5){
            $this->db->order_by('o.total_amount', $sSortDir_0); // 订单金额
        }else if($iSortCol_0 == 6){
            $this->db->order_by('o.addtime', $sSortDir_0); // 下单时间
        }else{
            $this->db->order_by('o.id desc');
        }
        $data = $this->pagination($this->tbOrder.' o');
        return $data;
    }

    /**
     * 销售统计走势
     * @param int   $startTime
     * @param int   $endTime
     * @param array $ci
     * @param bool $isOne       true 获取一条记录
     * @return array
     * @author heyu
     */
    public function getSalesStatistics($startTime, $endTime = 0, $ci = array(), $isOne = false){
        if (!$startTime){
            return array();
        }
        if ($endTime){
            $this->db->where('o.addtime <'.$endTime);
        }
        if (!empty($ci)){
            get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
            $this->db->join($this->mMerchant->tbShop.' s', 'o.merchant_id=s.merchant_id')
                ->where_in('s.county', $ci);
        }

        $this->db->select('sum(o.reality_amount) as amount,count(o.id) as order_num,FROM_UNIXTIME(o.addtime,"%Y-%m-%d") as time,
            TRUNCATE(sum(o.reality_amount)/count(o.id),2) as sign')
            ->join($this->tbUser.' u', 'u.id = o.consumer_id')
            ->where_in('o.status',array(4,5))
            ->where('o.addtime >='.$startTime)
            ->group_by('time');
        if ($isOne){
            return $this->getOne($this->tbOrder.' o');
        }
        $data = $this->getAll($this->tbOrder.' o');
        return $data;
    }

    /**
     * 运营总计
     * @param $startTime
     * @param int $endTime
     * @param array $ci
     * @param bool $isOne
     * @return array
     */
    public function getOperateStatisticsCount($startTime, $endTime = 0, $ci = array(),$merchant = 0){
        if (!$startTime){
            return array();
        }
        if ($endTime){
            $this->db->where('o.merchant_take_time <'.$endTime);
        }
        if (!empty($ci)){
            $this->db->where_in('ms.county', $ci);
        }
        if ($merchant){
            $this->db->where('s.id', $merchant);
        }
        $this->db->select('COUNT(*) AS total,SUM(total_amount) AS total_amount,SUM(bonus+postal_card+merchant_discount) AS discount_amount,SUM(reality_amount) AS reality_amount')
            ->join('merchant s', 'o.merchant_id=s.id','left')
            ->join('merchant_shop ms', 'ms.merchant_id = o.merchant_id','left')
            ->where_in('o.status',array(3,4,5,6))
            ->where('o.merchant_take_time >='.$startTime);
        return $this->getOne($this->tbOrder.' o');
    }

    /**运营总计列表
     * @param $startTime
     * @param int $endTime
     * @param array $ci
     * @param bool $isOne
     * @return array
     */
    public function getOperateStatisticsList($startTime, $endTime = 0, $ci = array(), $isOne = false){
        if (!$startTime){
            return array();
        }
        if ($endTime){
            $this->db->where('o.merchant_take_time <'.$endTime);
        }
        if (!empty($ci)){
            get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
            $this->db->join($this->mMerchant->tbShop.' s', 'o.merchant_id=s.merchant_id')
                ->where_in('s.county', $ci);
        }

        $this->db->select('COUNT(*) AS total,SUM(total_amount) AS total_amount,SUM(total_amount-reality_amount) AS discount_amount,SUM(reality_amount) AS reality_amount
                        ,FROM_UNIXTIME(o.merchant_take_time,"%Y-%m-%d") as time')
            ->where_in('o.status',array(3,4,5,6))
            ->where('o.merchant_take_time >='.$startTime)
            ->group_by('time');
        if ($isOne){
            return $this->getOne($this->tbOrder.' o');
        }
        $data = $this->getAll($this->tbOrder.' o');
        return $data;
    }
    /**
     * 按时间统计
     * @param $startTime
     * @param int $endTime
     * @param array $ci
     * @param bool $isOne
     * @return array
     */
    public function getOperateStatisticsDateList($startTime, $endTime = 0, $ci = array(),$all = false){
        if (!$startTime){
            return array();
        }
        if ($endTime){
            $this->db->where('o.merchant_take_time <'.$endTime);
        }
        if (!empty($ci)){
            $this->db->join('merchant_shop s', 'o.merchant_id=s.merchant_id')->where_in('s.county', $ci);
        }
        $this->db->select('FROM_UNIXTIME(o.merchant_take_time, "%Y-%m-%d") AS time,
                            SUM(if(change_amount!=0 AND change_amount is not NULL,change_amount, product_amount) +lunch_box_fee) AS product_amount,
                            SUM(shipping_fee) AS shipping_fee,
                            SUM(bonus) AS bonus,
                            SUM(postal_card) AS postal_card,
                            SUM(merchant_discount) AS merchant_discount,
                            SUM(reality_amount) AS reality_amount,
                            COUNT(*) AS total_order,
                            COUNT(DISTINCT o.consumer_id) AS total_user,
                            SUM(if(change_amount!=0 AND change_amount is not NULL,(total_amount - change_amount), 0)) AS change_amount,
                            TRUNCATE(sum(o.reality_amount)/count(o.id),2) as sign,
                            0 AS sale_order,0 AS sale_amount')
            ->from('consumer_order o')
            ->join('consumer u', 'u.id = o.consumer_id','left')
            ->where_in('o.status',array(3,4,5,6))
            ->where('o.merchant_take_time >='.$startTime)
            ->group_by('time');

        $sql1 =  $this->db->get_compiled_select();
        $this->db->reset_query();

        if ($endTime){
            $this->db->where('co.complete_time <'.$endTime);
        }
        if (!empty($ci)){
            $this->db->join('merchant_shop s', 'co.merchant_id=s.merchant_id')->where_in('s.county', $ci);
        }
        $this->db->select('FROM_UNIXTIME(co.complete_time, "%Y-%m-%d") AS time,0,0,0,0,0,0,0,0,0,0, COUNT( co.id ) AS sale_order, SUM(co.refund_amount) AS sale_amount')
            ->from('consumer_order_service co')
            ->join('consumer u', 'u.id = co.consumer_id','left')
            ->where('co.status',2)
            ->where('co.complete_time >='.$startTime)
            ->group_by('time');
        $sql2 =  $this->db->get_compiled_select();
        $this->db->reset_query();

        $this->db->select('a.time,SUM(a.product_amount) as product_amount,
	    SUM(a.shipping_fee) as shipping_fee,SUM(a.bonus) as bonus,SUM(a.postal_card) as postal_card,SUM(a.merchant_discount) as merchant_discount,SUM(a.reality_amount) as reality_amount,
	    SUM(a.total_order) as total_order,SUM(a.total_user) as total_user,SUM(a.change_amount) as change_amount,SUM(a.sign) as sign,SUM(a.sale_order) as sale_order,SUM(a.sale_amount) as sale_amount');
        $this->db->group_by('a.time');
        if($all){
            $data = $this->getAll('('.$sql1.' UNION '. $sql2 .' ) as a');
        }else{
            $data = $this->pagination('('.$sql1.' UNION '. $sql2 .' ) as a');
        }
        return $data;
    }

    public function getOperateStatisticsMerchantList($startTime, $endTime = 0, $ci = array(),$all = false){
        if (!$startTime){
            return array();
        }
        if ($endTime){
            $this->db->where('o.merchant_take_time <'.$endTime);
        }
        if (!empty($ci)){
            $this->db->where_in('ms.county', $ci);
        }

        $this->db->select('o.merchant_id,s.nickname,
                            SUM(if(change_amount!=0 AND change_amount is not NULL,change_amount, product_amount) +lunch_box_fee) AS product_amount,
                            SUM(shipping_fee) AS shipping_fee,
                            SUM(bonus) AS bonus,
                            SUM(postal_card) AS postal_card,
                            SUM(merchant_discount) AS merchant_discount,
                            SUM(reality_amount) AS reality_amount,
                            COUNT(*) AS total_order,
                            COUNT(DISTINCT o.consumer_id) AS total_user,
                            SUM(if(change_amount!=0 AND change_amount is not NULL,(total_amount - change_amount), 0)) AS change_amount,
                            TRUNCATE(sum(o.reality_amount)/count(o.id),2) as sign,
                            0 sale_order,
                            0 AS sale_amount')
            ->from('consumer_order o')
            ->join('consumer u', 'u.id = o.consumer_id','left')
            ->join('merchant s', 's.id = o.merchant_id','left')
            ->join('merchant_shop ms', 'ms.merchant_id = o.merchant_id','left')
            ->where_in('o.status',array(3,4,5,6))
            ->where('o.merchant_take_time >='.$startTime)
            ->group_by('o.merchant_id');

        $sql1 =  $this->db->get_compiled_select();
        $this->db->reset_query();

        if ($endTime){
            $this->db->where('co.complete_time <'.$endTime);
        }
        if (!empty($ci)){
            $this->db->where_in('ms.county', $ci);
        }

        $this->db->select('co.merchant_id,s.nickname,0,0,0,0,0,0,0,0,0,0,COUNT(co.id) AS sale_order,SUM(co.refund_amount) AS sale_amount')
            ->from('consumer_order_service co')
            ->join('consumer u', 'u.id = co.consumer_id','left')
            ->join('merchant s', 's.id = co.merchant_id','left')
            ->join('merchant_shop ms', 'ms.merchant_id = co.merchant_id','left')
            ->where('co.status',2)
            ->where('co.complete_time >='.$startTime)
            ->group_by('co.merchant_id');

        $sql2 =  $this->db->get_compiled_select();
        $this->db->reset_query();

        $this->db->select('a.merchant_id,a.nickname,SUM(a.product_amount) as product_amount,
	    SUM(a.shipping_fee) as shipping_fee,SUM(a.bonus) as bonus,SUM(a.postal_card) as postal_card,SUM(a.merchant_discount) as merchant_discount,SUM(a.reality_amount) as reality_amount,
	    SUM(a.total_order) as total_order,SUM(a.total_user) as total_user,SUM(a.change_amount) as change_amount,SUM(a.sign) as sign,SUM(a.sale_order) as sale_order,SUM(a.sale_amount) as sale_amount');
        $this->db->group_by('a.merchant_id');
        if($all){
            $data = $this->getAll('('.$sql1.' UNION '. $sql2 .' ) as a');
        }else{
            $data = $this->pagination('('.$sql1.' UNION '. $sql2 .' ) as a');
        }
        return $data;
    }

    /**
     * 平台资金信息
     * @param int $startTime        开始时间
     * @param int $endTime          结束时间
     * @param bool $isOne
     * @param int $page
     * @param int $pageNumber
     * @return array
     * @author heyu
     */
    public function getWebMoneyList($startTime = 0, $endTime = 0, $isOne = true, $page = 0, $pageNumber = 0){
        if ($startTime){
            $this->db->where('addtime >= '.$startTime);
        }
        if ($endTime){
            $this->db->where('addtime < '.$endTime);
        }
//        if ($status){
//            $this->db->where(array('status' => $status));
//        }else{
//            $this->db->where_in('status', array(4,5));
//        }
        $this->db->where_in('status', array(4,5));
        $this->db->select('sum(reality_amount) as reality_amount,sum(total_amount) as total_amount,
            count(id) as order_num,count(if(status != 6 || status !=7 , id, null)) as total,
            FROM_UNIXTIME(addtime,"%Y-%m-%d") as time');
        if ($isOne){
            return $this->getOne($this->tbOrder);
        }else{
            $this->db->select('sum(product_amount) as product_amount,sum(shipping_fee) as shipping_fee');
            $this->db->group_by('time')
                ->order_by('time desc');
            if ($page && $pageNumber) {
                $tA = $this->appPage($this->tbOrder, $page, false, $pageNumber);
                $tA = $tA['list'];
            }else{
                $tA = $this->pagination($this->tbOrder);
            }
            return $tA;
        }
    }

    /**
     * 根据时间获取订单明细列表
     * @param $time
     * @param $export
     * @return array
     */
    public function getOrderListByTime($time, $export = array()){
        if(!$time){
            return array();
        }
        $time = strtotime($time);
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($iSortCol_0 == 1){
            $this->db->order_by('o.id', $sSortDir_0); // 订单id
        }else if($iSortCol_0 == 2){
            $this->db->order_by('o.code', $sSortDir_0); // 订单号
        }else if($iSortCol_0 == 4){
            $this->db->order_by('o.product_amount', $sSortDir_0); // 商品总价
        }else if($iSortCol_0 == 5){
            $this->db->order_by('o.shipping_fee', $sSortDir_0); // 物流价格
        }else if($iSortCol_0 == 6){
            $this->db->order_by('o.total_amount', $sSortDir_0); // 订单总价
        }else if($iSortCol_0 == 8){
            $this->db->order_by('o.addtime', $sSortDir_0); // 下单日期
        }else{
            $this->db->order_by('o.addtime desc'); // 下单日期
        }
        $this->db->select('o.id,o.code,u.mobile,o.product_amount,o.total_amount,o.reality_amount,o.shipping_fee,
            o.addtime')
            ->join($this->tbUser.' u', 'o.consumer_id=u.id')
            ->where('o.addtime >=', $time)
            ->where('o.addtime <', strtotime('+1day', $time))
            ->where_in('o.status', array(4,5));
        if(empty($export)){
            return $this->pagination($this->tbOrder.' o');
        }else{
            $tA = $this->appPage($this->tbOrder.' o', $export['page'], false, $export['pageNumber']);
            return $tA['list'];
        }
    }

	//////////////////////////////////////////////
	//+------------------------------------------
	//|	售后服务
	//+--------------------------------------------

	/**
	 * 获取售后服务详情
	 * @param string    $code
	 * @param int       $orderId
	 * @param int       $orderProductId
	 * @param int       $consumerId         用户id
	 * @param int       $merchant_id        商家id
	 * @param int       $serviceId          售后id
	 * @return array|array
	 * @author zyl
	 */
    public function getServiceInfo($code,$orderId = 0,$orderProductId = 0,$consumerId = 0,$merchant_id = 0,$serviceId = 0){
    	if (! $code && ! $orderId && ! $orderProductId && ! $serviceId){
			return array();
		}

		if ($code){
			$this->db->where('os.code',$code);
		}
		if ($serviceId){
			$this->db->where('os.id',$serviceId);
		}
		if ($orderId){
			$this->db->where('os.order_id',$orderId);
		}
		if ($orderProductId){
			$this->db->where('os.order_product_id',$orderProductId);
		}

		if ($consumerId){
			$this->db->where('os.consumer_id',$consumerId);
		}

        if ($merchant_id){
            $this->db->where('os.merchant_id',$merchant_id);
        }

		$this->db->select('os.id,os.code,os.reason,os.refund_amount,os.merchant_id,os.consumer_id,
            os.order_id,os.order_status,os.remark,os.addtime,os.pic,o.pay_type,o.reality_amount,os.complete_remark,
            os.platform_remark,os.status,o.code as order_code,os.complete_time,u.jpush_code')
            ->join($this->tbOrder.' o','o.id = os.order_id')
            ->join($this->tbUser.' u','u.id = os.consumer_id')
            ->order_by('os.id desc');

		$tA = $this->getOne($this->tbOrderService.' os');

		if ($tA){
			$tA['addtime'] = date('Y-m-d H:i:s',$tA['addtime']);
			$tA['complete_time'] = isset($tA['complete_time']) ? date('Y-m-d H:i:s',$tA['complete_time']) : '';
			$tA['status_name'] = $this->SERVICE_TYPE[$tA['status']];
			$tA['status_format_str'] = $this->serviceType($tA['status'], true);
            $tA['complete_remark'] = $tA['complete_remark']?$tA['complete_remark']:'';
            $tA['platform_remark'] = $tA['platform_remark']?$tA['platform_remark']:'';

            $pic = array();
            if (!empty($tA['pic'])){
                $pic = json_decode($tA['pic']);
                foreach ($pic as $k => $v){
                    $pic[$k] = base_url($v);
                }
            }
            $tA['pic'] = $pic;
		}

		return $tA;
	}

    public function getProductList($orderId = 0, $serviceId = 0, $consumerId = 0, $merchant_id = 0){
        if (! $orderId  && ! $serviceId){
            return array();
        }
        if ($serviceId){
            $this->db->where('os.id',$serviceId);
        }
        if ($orderId){
            $this->db->where('os.order_id',$orderId);
        }
        if ($consumerId){
            $this->db->where('os.consumer_id',$consumerId);
        }
        if ($merchant_id){
            $this->db->where('os.merchant_id',$merchant_id);
        }
        $this->db->select('op.reality_amount,p.name,op.price,op.quantity,v.property')
            ->join($this->tbOrder.' o','o.id = os.order_id')
            ->join($this->tbOrderProduct.' op','op.order_id = o.id')
            ->join($this->tbUser.' u','u.id = os.consumer_id')
            ->join($this->tbProduct.' p','p.id = op.product_id')
            ->join($this->tbProductVariant.' v', 'v.product_id = op.product_id and v.sort = op.variant_id', 'left')
            ->group_by('op.id')
            ->order_by('os.id desc');
        $tA = $this->getAll($this->tbOrderService.' os');
        foreach ($tA as $k => $v){
            $tA[$k]['reality_amount'] = sprintf('%.2f',$v['quantity']*$v['price']);
            $tA[$k]['property'] = $v['property']? '规格：'. implode(',',json_decode($v['property'], true)):'暂无规格';
        }
        return $tA;
    }

    /**
     * 获取商家未处理的售后订单
     * @param $merchantId 商家id
     */
    public function getServiceOrderCount($merchantId){
        $this->db->where(array('merchant_id' => $merchantId,'status' => 3));

        return $this->count($this->tbOrderService);
    }

    /**
     * 获取同一订单，已申请售后的次数
     * @param $consumerId
     */
    public function hasOrderServiceCount($orderId, $consumerId){
        if(!$orderId || !$consumerId){
            return 0;
        }
        $this->db->where(array('consumer_id' => $consumerId,'order_id' => $orderId));

        return $this->count($this->tbOrderService);
    }

	/**
	 * 获取售后服务列表
	 * @param integer $consumerId 消费id
	 * @param integer $merchantId 商家id
	 * @param integer $status  状态 0全部 1-售后拒绝  2-售后完成 3-售后中
	 * @param number $page 分页
	 * @return array|array|array[]|number[]|unknown[]
	 * @author zyl  khj（增加商家id）
	 */

    public function appGetServiceList($consumerId, $merchantId = 0, $page = 1, $status = 0){
        if ( ! $consumerId && !$merchantId){
            return array();
        }

        if($consumerId){
            $this->db->where('os.consumer_id',$consumerId);
        }

        if($merchantId){
            $this->db->where('os.merchant_id',$merchantId);
        }

        if($status){
            $this->db->where('os.status', $status);
        }
        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		$this->db
		     ->select('os.id,os.merchant_id,os.code,os.status,os.refund_amount,p.name as title,p.icon,m.portrait,m.nickname as shop_name,
		     op.total')
            ->join($this->tbOrder.' o','o.id = os.order_id')
            ->join('(SELECT order_id,product_id,count(id) as total from `consumer_order_product` group by order_id)'.' op','op.order_id = os.order_id')
            ->join($this->tbProduct.' p','p.id = op.product_id')
            ->join($this->mMerchant->tbUser.' m','m.id = os.merchant_id')
            ->order_by('os.addtime desc')
            ->group_by('os.order_id');


        $tA = $this->appPage('(SELECT * from '.$this->tbOrderService.'  ORDER BY id desc)'.' os', $page);
//        p($this->db->last_query());
        //重组数据
        foreach ($tA['list'] as $k=>$v){
            $tA['list'][$k]['status_name'] = $this->SERVICE_TYPE[$v['status']];
            $tA['list'][$k]['icon'] = getImage($v['icon'],'xs');
            $tA['list'][$k]['portrait'] = $v['portrait']?getImage($v['portrait'],'og'):getDefaultPortrait(2);
            $title = $v['title'];
            $title = mb_strlen($title,'utf8') > 10 ? mb_substr($title, 0, 10, 'utf-8').'...' : $title;
            $total = $v['total'];
            if($total > 1){
                $title = $title.'等'.$total.'件商品';
            }else{
                $title = $title.$total.'件商品';
            }
            $tA['list'][$k]['title'] = $title;

        }

        return $tA['list'];
    }

	/**
	 * 保存产品售后信息
	 * @param array $data 数据
	 * @param int   $code
	 * @param int   $id
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function saveService($data,$code = 0, $id = 0){
		if ($code || $id){
		    if ($code) {
                $this->db->where('code', $code);
            }
            if ($id){
                $this->db->where('id', $id);
            }
			$query = $this->update($this->tbOrderService, $data);
			return $query === false ? false : true;
		}else{
			return $this->insert($this->tbOrderService, $data);
		}
	}

    /**
     * 商家营业统计（营业额 = 支付完成,实际收款=确认收货）
     * @param $merchantId  商家id
     * @return array
     * @author khj
     */
	public function merchantOrderStatistics($merchantId, $mini = false){
	    if(!$merchantId) return array();
        //本月
        $BeginDate = date('Y-m-1');
        $start = strtotime($BeginDate);
        $end = strtotime("$BeginDate +1 month -1 day");

        if($mini){
            //实际收款
            $this->db->select('sum(reality_amount) as reality_amount,
                            sum(if(addtime >= '.$start.' and addtime < '.$end.', reality_amount, null)) as reality_month_amount')
                ->where('merchant_id', $merchantId)
                ->where_in('status', array(4,5));

            return $this->getOne($this->tbOrder);
        }

        //营业额
        $this->db->select('count(distinct consumer_id) as user,count(distinct id) as orders,
                            sum(reality_amount) as amount,
                            count(if(addtime >= '.$start.' and addtime < '.$end.', id, null)) as month_total,
                            sum(if(addtime >= '.$start.' and addtime < '.$end.', reality_amount, null)) as month_amount')
                ->where('merchant_id', $merchantId)
                ->where_in('status', array(2,3,4,5));


       return $this->getOne($this->tbOrder);
    }

    /**
     * 获取商家财务统计收益明细
     * @param $merchantId  商家id
     * @param $page        页码
     * @param $year       年份
     * @param $month       月份
     * @param $type       (1营业额 = 支付完成,2实际收款=确认收货)
     * @return array
     */
    public function appMerchantOrderStatisticsList($merchantId, $year, $month, $page, $type){
	    if(!$merchantId) return array();

        $start_date=date("Y-m-d H:i:s", mktime(0, 0 , 0,$month,1,$year));
        $end_time=strtotime("$start_date +1 month");
        $start_time=strtotime($start_date);

        if($type == 1){
            $this->db->where_in('status', array(2,3,4,5));
        }else{
            $this->db->where_in('status', array(4,5));
        }
	    $this->db->select('id as order_id,code,reality_amount,addtime')
                 ->where('merchant_id', $merchantId)
                 ->where(array('addtime > '=>$start_time,'addtime <'=>$end_time))
                 ->order_by('addtime desc');

        $tA = $this->appPage($this->tbOrder, $page);

        foreach ($tA['list'] as $k=>$v){
            $tA['list'][$k]['addtime'] = dateFormat($v['addtime'],true);
        }

        return $tA;
    }

    /**
     * 通过商品订单id查询售后订单
     * @param $orderId
     * @return array|bool
     * @author heyu
     */
    public function getServiceListByOrderId($orderId,$mini = false){
        if (!$orderId){
            return false;
        }
        if($mini){
            $this->db->select('id,status,order_product_id')
                ->where(array('order_id' => $orderId))
                ->order_by('id desc');
            return $this->getAll($this->tbOrderService);
        }
        $this->db->where(array('order_id' => $orderId));
        return $this->getAll($this->tbOrderService);
    }

    /**
     * 后台查看售后订单
     * @param int   $merchantId
     * @param int   $consumerId
     * @param array $ci             区域
     * @param array $export         导出
     * @return array
     * @author heyu
     */
    public function adminPcGetOrderServiceList($merchantId = 0, $consumerId = 0, $ci = array(), $export = array()){
        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $serviceCode = trim(get('serviceCode'));
        $orCode = trim(get('orCode'));
        $serviceMerchant = trim(get('serviceMerchant'));
        $productName = trim(get('productName'));
        $status = (int)get('serviceType');
        $dateFrom = strtotime(get('service_add_time_from'));
        $dateTo = strtotime(get('service_add_time_to'));
        $completeDateFrom = strtotime(get('service_complete_time_from'));
        $completeDateTo = strtotime(get('service_complete_time_to'));
        $time = trim(get('time')); // 销售统计查看当天销售订单
        $take_time_from = strtotime(get('take_time_from'));
        $take_time_to = strtotime(get('take_time_to'));

        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if($merchantId){
            $this->db->where('o.merchant_id', $merchantId);
        }
        if($consumerId){
            $this->db->where('o.consumer_id', $consumerId);
        }
        if (!empty($ci)){
            $this->db->where_in('s.county', $ci);
        }
        if ($serviceCode){
            $this->db->like(array('os.code' => $serviceCode));
        }
        if ($orCode){
            $this->db->like(array('o.code' => $orCode));
        }
        if ($serviceMerchant){
            $this->db->like(array('s.shop_name' => $serviceMerchant));
        }
        if ($productName){
            $this->db->like(array('p.name' => $productName));
        }
        if ($status){
            $this->db->where(array('os.status' => $status));
        }
        if($dateFrom){
            $this->db->where('os.addtime >=', $dateFrom);
        }
        if($dateTo){
            $this->db->where('os.addtime <', strtotime('+1day', $dateTo));
        }
        if($completeDateFrom){
            $this->db->where('os.complete_time >=', $completeDateFrom);
        }
        if($completeDateTo){
            $this->db->where('os.complete_time <', strtotime('+1day', $completeDateTo));
        }
        /*if($take_time_from){
            $this->db->where('o.merchant_take_time >=', $take_time_from);
        }
        if($take_time_to){
            $this->db->where('o.merchant_take_time <', strtotime('+1day', $take_time_to));
        }*/
        if ($time){
            $starTime = strtotime($time.' 00:00:00');
            $endTime = $starTime+86400;
            $this->db->where_in('os.status',2)
                ->where('(os.complete_time >='.$starTime.' and os.complete_time <='.$endTime.')');
        }
        if ($merchantId || $consumerId){
            $iSortCol_0 += 1;
        }

        if ($iSortCol_0 == 5){
            $this->db->order_by('os.refund_amount', $sSortDir_0); // 退款金额
        }else if($iSortCol_0 == 6){
            $this->db->order_by('os.addtime', $sSortDir_0); // 申请时间
        }else{
            $this->db->order_by('os.addtime desc');
        }

        $this->db->select('os.id,os.merchant_id,os.consumer_id,os.code,os.refund_amount,os.remark,os.status,os.addtime,os.complete_time,
            s.shop_name,p.name,o.code as order_code')
            ->join($this->mMerchant->tbUser.' mu', 'mu.id = os.merchant_id')
            ->join($this->mMerchant->tbShop.' s', 's.merchant_id = mu.id')
            ->join($this->tbOrder.' o', 'os.order_id = o.id')
            ->join($this->tbOrderProduct.' op', 'o.id = op.order_id')
            ->join($this->tbProduct.' p', 'op.product_id = p.id')
            ->group_by('os.code');

        if (empty($export)){
            $data = $this->pagination($this->tbOrderService.' os');

            return $data;
        }else{
            $tA = $this->appPage($this->tbOrderService.' os', $export['page'], false, $export['pageNumber']);
            return $tA['list'];
        }
    }

    /**
     * 获取商城状态
     * @param int       $key
     * @param bool      $show
     * @return array|mixed|string
     * @author heyu
     */
    public function serviceType($key = null, $show = false){

        if($key === null){
            return $this->SERVICE_TYPE;
        }

        if($key !== null && ! isset($this->SERVICE_TYPE[$key])){
            return '';
        }

        if( ! $show ){
            return $this->SERVICE_TYPE[$key];
        }

        if ($key == 4) {
            return '<span class="label badge-default">' . $this->SERVICE_TYPE[$key] . '</span>';
        } else if ($key == 2) {
            return '<span class="label label-success">' . $this->SERVICE_TYPE[$key] . '</span>';
        } else if ($key == 3) {
            return '<span class="label label-warning">' . $this->SERVICE_TYPE[$key] . '</span>';
        }
        return '';
    }

    /**
     * 24小时未处理售后订单
     * @param bool $isCount
     * @return array
     * @author heyu
     */
    public function getTwentyFourHoursUntreatedOrderServiceList($isCount = false, $ci = array()){
        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $code = trim(get('fHOrderCode'));
        $expenseType = (int)get('fHExpenseType');
        $payType = (int)get('fHPayType');
        $status = (int)get('fHOrderStatus');
        $amountFrom = get('fh_amount_from'); // 订单总金额大于等于
        $amountTo = get('fh_amount_to'); // 订单总金额小于等于
        $merchant = trim(get('fHMerchant'));
        $consumer = trim(get('fHConsumer'));
        $dateFrom = strtotime(get('fh_add_time_from'));
        $dateTo = strtotime(get('fh_add_time_to'));

        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if($dateFrom){
            $this->db->where('o.addtime >=', $dateFrom);
        }
        if($dateTo){
            $this->db->where('o.addtime <', strtotime('+1day', $dateTo));
        }
        if($code){
            $this->db->like('o.code', $code);
        }
        if($expenseType){
            $this->db->where('o.expense_type', $expenseType);
        }
        if($payType){
            $this->db->where('o.pay_type', $payType);
        }
        if($status){
            $this->db->where('o.status', $status);
        }
        if($amountFrom){
            $this->db->where('o.total_amount <=', $amountFrom);
        }
        if($amountTo){
            $this->db->where('o.total_amount <=', $amountTo);
        }
        if($merchant){
            $this->db->like('s.shop_name', $merchant);
        }
        if($consumer){
            $this->db->like('u.nickname', $consumer);
        }
        if($dateFrom){
            $this->db->where('o.addtime >=', $dateFrom);
        }
        if($dateTo){
            $this->db->where('o.addtime <', strtotime('+1day', $dateTo));
        }
        if (!empty($ci)){
            $this->db->where_in('s.county', $ci);
        }

        if ($iSortCol_0 == 5){
            $this->db->order_by('os.refund_amount', $sSortDir_0); // 退款金额
        }else if($iSortCol_0 == 6){
            $this->db->order_by('os.addtime', $sSortDir_0); // 申请时间
        }else{
            $this->db->order_by('os.addtime desc');
        }

        $time = time()-86400;
        $this->db->select('os.id,os.merchant_id,os.consumer_id,os.code,os.refund_amount,os.remark,os.status,os.addtime,
            s.shop_name,p.name,o.code as order_code')
            ->join($this->mMerchant->tbUser.' mu', 'mu.id = os.merchant_id')
            ->join($this->mMerchant->tbShop.' s', 's.merchant_id = mu.id')
            ->join($this->tbOrderProduct.' op', 'os.order_product_id = op.id')
            ->join($this->tbOrder.' o', 'os.order_id = o.id')
            ->join($this->tbProduct.' p', 'op.product_id = p.id')
            ->where(array('os.status' => 3, 'os.addtime < '.$time));
        if ($isCount){
            return $this->count($this->tbOrderService.' os');
        }
        $data = $this->pagination($this->tbOrderService.' os');
        return $data;
    }

    /**
     * 获取商户成交率
     * 规则：(1-（售后商品总数/付款商品总数（sum商品数量））*100%)
     * @param $merchantId       int     商户id
     * @return int
     * @author heyu
     */
    public function getSuccessOrderRate($merchantId){
        if (!$merchantId){
            return '0';
        }
        //付款商品总数
        $this->db->select('count(DISTINCT p.id) as total, count(DISTINCT s.order_product_id) as service')
                 ->join($this->tbOrderProduct.' p', 'p.order_id = o.id')
                 ->join($this->tbOrderService.' s', 's.order_id = o.id and s.order_product_id = p.id','left')
            ->where(array('o.merchant_id' => $merchantId))
            ->where_in('o.status', array(2,3,4,5));
        $tA = $this->getOne($this->tbOrder.' o');

        $n = '0';
        if (!empty($tA) && $tA['total'] > 0){
            $n = round(1-($tA['service']/$tA['total']), 2)*100;
        }

        return $n.'%';
    }

    /**
     * 获取可操作订单数量（待发货 待核销总订单数量）
     * @param $merchantId  商家id
     * @param $consumerId  消费者id
     * @return int
     */
    public function getOperateOrderNumber($merchantId, $consumerId = 0, $merchantCount = false){
        if(!$merchantId && !$consumerId) return 0;
        $order_expire = (time() - getCustomConfig('order_expire') * 60);
        $expect_take_time = (int)getCustomConfig('expect_take_time');//接单有效时间
        $expect_take_time = time() - $expect_take_time * 60;
        if($consumerId){
            $this->db->select('count(if(expense_type = 1 and status = 1 and addtime > '.$order_expire.', id, null)) as delPayNumber,
                                count(if(expense_type = 1 and status = 2, id, null)) as delAcceptNumber,
                                count(if(expense_type = 1 and status = 3, id, null)) as delShipNumber,
                                count(if(expense_type = 1 and status = 4, id, null)) as delCommentNumber,
                                count(if(expense_type = 2 and status = 1 and addtime > '.$order_expire.', id, null)) as storePayNumber,
                                count(if(expense_type = 2 and status = 3, id, null)) as storeCheckNumber,
                                count(if(expense_type = 2 and status = 4, id, null)) as storeCommentNumber,
                                ')
                ->where('consumer_id', $consumerId);
            $tA = $this->getOne($this->tbOrder);
            return $tA;
        }
        if($merchantCount && $merchantId){
            $this->db->select('count(if(expense_type = 1 and status = 1 and addtime > '.$order_expire.', id, null)) as delPayNumber,
                                count(if(expense_type = 1 and status = 2, id, null)) as delAcceptNumber,
                                count(if(expense_type = 1 and status = 3, id, null)) as delShipNumber,
                                count(if(expense_type = 2 and status = 1 and addtime > '.$order_expire.', id, null)) as storePayNumber,
                                count(if(expense_type = 2 and status = 3, id, null)) as storeCheckNumber
                                ')
                ->where('merchant_id', $merchantId);
            $tA = $this->getOne($this->tbOrder);
            return $tA;
        }
        $this->db->select('count(if(expense_type = 1 and status = 2, id, null)) as delivery_number,
                            count(if(expense_type = 2 and status = 3, id, null)) as verification_number')
            ->where('merchant_id', $merchantId);

        $tA = $this->getOne($this->tbOrder);

        return $tA['delivery_number'] + $tA['verification_number'];
    }

/***********************************************订单操作记录***********************************************************/

    /**
     * 获取订单操作列表
     * @return array
     * @author heyu
     */
    public function adminPcGetOrderLogList(){
        get_instance()->loadModel('AdmUserModel', 'mAdm', 'admin');
        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        get_instance()->loadModel('DlnUserModel', 'mDln', 'deliveryman');
        $orderId = (int)get('order_id');
        $this->db->select("ol.order_id,ol.order_status,ol.type, 
            case (ol.type) when 1 then (a.name) when 3 then (s.shop_name) when 4 then (d.name) else (m.nickname) end as user_name,
            ol.note,ol.addtime")
            ->join($this->mAdm->tbUser.' a', 'a.id=ol.user_id and ol.type=1', 'left')
            ->join($this->mMerchant->tbUser.' u', 'u.id=ol.user_id and ol.type=3', 'left')
            ->join($this->mDln->tbUser.' d', 'd.id=ol.user_id and ol.type=4', 'left')
            ->join($this->mMerchant->tbShop.' s', 's.merchant_id=u.id', 'left')
            ->join($this->tbUser.' m', 'm.id=ol.user_id and ol.type=2', 'left')
            ->where(array('ol.order_id' => $orderId))
            ->order_by('ol.addtime desc');

        $data = $this->pagination($this->tbOrderLog.' ol');
        return $data;
    }

    /**
     * 添加订单操作记录
     * @param $id       int         订单id
     * @param $status   int         订单状态
     * @param $note     string      操作备注
     * @param $port     string
     * @param $userId   int         用户id
     * @return int
     * @author heyu
     */
    public function saveOrderLog($id, $status, $note, $port = 'admin', $userId = 0){
        if ($port == 'admin' || $port == 'county'){
            $type = 1;
        }else if ($port == 'consumer'){
            $type = 2;
        }else if ($port == 'merchant'){
            $type = 3;
        }else if ($port == 'deliveryman'){
            $type = 4;
        }

        $data = array(
            'order_id' => $id,
            'order_status' => $status,
            'type' => $type,
            'user_id' => $userId,
            'note' => $note,
            'addtime' => time()
        );

        return $this->insert($this->tbOrderLog, $data);
    }

    /**
     * 删除操作记录
     * @param $orderId      int     订单id
     * @return bool
     * @author heyu
     */
    public function deleteOrderLog($orderId){
        if (!$orderId){
            return false;
        }
        $this->db->where(array('order_id' => $orderId));
        return $this->delete($this->tbOrderLog);
    }

    /**
     * 查询是否满足首单减免
     * @param $merchantId  商家id
     * @return array
     */
    public function firstOrderByMerchantId($merchantId, $conumserId){

        if(!$merchantId || !$conumserId) return array();
        get_instance()->loadModel('MerchantUserModel', 'mMMuser', 'merchant');

//        $this->db->select('count(if(o.consumer_id = '.$conumserId.' and o.status in(1,2,3,4,5,6,8),o.id,null)) as count,
//                            u.id as merchant_id,u.first_order_reduce')
//                 ->join($this->mMMuser->tbUser.' u', 'u.id = o.merchant_id')
//                ->where_in('u.id', $merchantId)
//                ->group_by('u.id');
//        $tA = $this->getAll($this->tbOrder. ' o');

        $this->db->select('count(if(o.consumer_id = '.$conumserId.' and o.status in(1,2,3,4,5,6,8),o.id,null)) as count,
                            u.id as merchant_id,u.first_order_reduce')
            ->join($this->tbOrder.' o', 'u.id = o.merchant_id', 'left')
            ->where_in('u.id', $merchantId)
            ->group_by('u.id');
        $tA = $this->getAll($this->mMMuser->tbUser. ' u');

        $data = array();
        foreach ($tA as $v){
            $data[$v['merchant_id']]= $v;
        }

        return $data;
    }

    /***********************************************通用订单操作方法***********************************************************/

    /**
     * 减商品库存, 增加库存
     * @param $id   int     订单id
     * @return array
     */
    public function reduceStocks($id, $add = false){
        if(!$id) array('status' => 0,'message' => '订单id必须');

        // 获取商品详情
        $ProductList = $this->getOrderProductInfoByIds(array(), $id, 0, false, true);

        get_instance()->loadModel('ConsumerProductModel', 'mProduct', 'consumer');

        // 减少商品库存
        $productData = array();
        $downProduct = array();//下架商品
        $msg = array();
        foreach ($ProductList[$id] as $p => $pv){
            if ($pv['variant_id'] > 0){
                // 有规格获取规格数据
                if($pv['variant_is_limited'] != 2){
                    if ($add == false && $pv['variant_quantity'] < $pv['quantity']){
                        return array('status' => 0,'message' => $pv['name'].'库存不足不能发货');
                    }
                    // 有限库存减少库存数量
                    if($add){
                        $quantity = $pv['variant_quantity']+$pv['quantity'];
                    }else{
                        $quantity = $pv['variant_quantity']-$pv['quantity'];
                    }

                    $variantData = array(
                        'quantity' => $quantity
                    );

                    $rS = $this->mProduct->savePropertyVariant($variantData, $pv['product_id'], $pv['variant_id']);
                    if (!$rS){
                        return array('status' => 0,'message' => $pv['name'].'库存更新失败');
                    }

                    if($quantity == 0){
                        //商品预警
                        $title = '库存预警';
                        $content = '您的商品:'.$pv['name'].'，库存已不足，请及时调整以免影响用户购买， 若商品已无销售请设置为下架';
                        $msg[] = array(
                            'merchant_id' => $pv['merchant_id'],
                            'order_id' => 0,
                            'type' => 2,
                            'title' => $title,
                            'content' => $content,
                            'content_detail' => $content,
                            'addtime' => time(),
                        );
                        MerchantJpush($title, $content, 1, array($pv['jpush_code']), 2);
                        //其他规格库存是否大于0
                        $hasQ = $this->mProduct->hasQuantity($pv['product_id'],$pv['variant_id']);
                        if(!$hasQ){
                            //自动下架商品
                            $downProduct[] = array(
                                'id' => $pv['product_id'],
                                'status' => 1
                            );
                        }
                    }
                }
            }else{
                // 没有规格获取商品数据
                if($pv['product_is_limited'] != 2) {
                    if ($add == false && $pv['product_quantity'] < $pv['quantity']){
                        return array('status' => 0,'message' => $pv['name'].'库存不足不能发货');
                    }
                    if($add){
                        $quantity = $pv['product_quantity'] + $pv['quantity'];
                    }else{
                        $quantity = $pv['product_quantity'] - $pv['quantity'];
                    }

                    $productData[] = array(
                        'id' => $pv['product_id'],
                        'quantity' => $quantity
                    );
                    if($quantity == 0){
                        //商品预警
                        $title = '库存预警';
                        $content = '您的商品:'.$pv['name'].'，库存已不足，请及时调整以免影响用户购买， 若商品已无销售请设置为下架';
                        $msg[] = array(
                            'merchant_id' => $pv['merchant_id'],
                            'order_id' => 0,
                            'type' => 2,
                            'title' => $title,
                            'content' => $content,
                            'content_detail' => $content,
                            'addtime' => time(),
                        );
                        MerchantJpush($title, $content, 1, array($pv['jpush_code']), 2);
                        //自动下架商品
                        $downProduct[] = array(
                            'id' => $pv['product_id'],
                            'status' => 1
                        );

                    }
                }
            }
        }
        if($downProduct){
            //自动下架商品
            $this->mProduct->saveBatchProduct($downProduct, 'id');
        }
        // 减少商品库存
        if (!empty($productData)){
            $pr = $this->mProduct->saveBatchProduct($productData, 'id');
            if (!$pr){

                return array('status' => 0,'message' => '库存更新失败');
            }
        }
        if($msg){
            get_instance()->loadModel('MerchantMessageModel', 'mMerMsg', 'merchant');
            $this->mMerMsg->saveBatch($msg);
        }
        return array('status' => 1, 'message' => '成功');
    }

    /**
     * 确认收货
     * @param int       $id       订单id
     * @param int       $merchantId      商家id
     * @param string    $note     操作备注
     * @param string    $port     操作
     * @param string    $userId     操作用户
     * @return bool
     * @author heyu
     */
    public function _confirmReceipt($id, $note= '', $merchantId = 0, $port = 'admin', $userId = 0){

        if(!$id) return array('status' => 0,'message' => '订单id必须');
        if(!$note) return array('status' => 0,'message' => '操作备注必须');
        // 查看订单是否存在
        $info = $this->appGetInfo($id);
        if (empty($info)){
            return array('status' => 0,'message' => '订单不存在');
        }
        if ($info['status'] != 3){
            return array('status' => 0,'message' => '不能确认收货');
        }
        //验证订单是否存在售后
        //商品信息
//        $productList = $this->getOrderProductList($id,  0,$merchantId);
//
//        if(!$productList){
//           return array('status' => 0,'message' => '无效的核销码');
//        }


        $merchantIncome = $info['merchant_income'];//商家收益

        if($info['after_sale'] == 3){
            return array('status' => 0,'message' => '该订单正在售后中，请核实');
        }

        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        get_instance()->loadModel('MerchantBalanceModel', 'mBalance', 'merchant');


        // 修改订单状态
        $tA = $this->save(array('status' => 4, 'confirmtime' => time()), 0, $id);
        if (!$tA){
            return array('status' => 0,'message' => '保存失败');
        }
        // 打款给商家
        // 查看商家信息
        $merInfo = $this->mMerchant->getInfo($info['merchant_id'], 0, true);

        $bal = $this->mMerchant->save(array('balance' => $merInfo['balance']+$merchantIncome), $info['merchant_id']);
        if(!$bal){
            return array('status' => 0,'message' => '保存失败');
        }
        //添加余额记录
        $balanceLog = array(
            'merchant_id' => $info['merchant_id'],
            'type' => 5,
            'pay_type' => 1,
            'amount' => $merchantIncome,
            'percent' => $info['percent'],
            'param' => $id,
            'status' => 2,
            'addtime' => time(),
            'confirm_time' => time(),
        );
        $bLog = $this->mBalance->save($balanceLog);
        if (!$bLog){
            return array('status' => 0,'message' => '保存失败');
        }

        $rS = $this->saveOrderLog($id, '待评价', $note, $port, $userId);
        if (!$rS){
            return array('status' => 0,'message' => '保存失败');
        }

        return array('status' => 1,'message' => '保存成功');
    }

    /**
     * 交易关闭 退款
     * @param $consumerId  消费者id
     * @param $refund   退款金额
     * @param $payType  支付方式
     * @param $wxType 是否是微信公众支付
     * @param $payCode  支付单号
     * @param $code  退款单号 即订单号
     * @return array
     */
    public function _orderRefund($orderId,$consumerId, $refund, $payType,$wxType,$payCode,$code){
        get_instance()->loadModel('ConsumerPayModel', 'mPay', 'consumer'); // 用户支付模型
        get_instance()->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
        get_instance()->loadModel('ConsumerBuyModel', 'mBuy', 'consumer'); // 资金账户模型

        if(!$orderId || !$consumerId || !$refund || !$payType || !$payCode || !$code){
            return array('status' => 0, 'message' => '参数错误');
        }
        if ($payType == 1){
            // 余额支付 -- 增加用户余额
            $con = $this->mConsumer->setConsumer($consumerId, $refund);
            if (!$con){
                return array('status' => 0, 'message' => '增加用户余额失败');
            }
        }else if ($payType == 2){
            // 微信支付退款到微信
            $db['pay_type'] = 2;
            if ($wxType == 2){ // 微信公众号只退款
                $payTa = $this->mPay->WeChatRefund($payCode, $refund, $refund, $code);
            }else{ // APP微信退款
                $payTa = $this->mPay->wxRefund($payCode, $refund, $refund, $code);
            }
            if ($payTa['return_code'] == 'FAIL'){
                return array('status' => 0, 'message' => '退款失败，错误原因：'.$payTa['return_msg']);
            }
        }else if($payType == 3){
            // 支付宝支付退款到支付宝
            $db['pay_type'] = 3;
            $payTa = $this->mPay->zfbRefund($payCode, $refund, $code);
            if ($payTa != 10000){
                return array('status' => 0, 'message' => '退款失败');
            }
        }else{
            return array('status' => 0, 'message' => $payType.'支付方式有误');
        }
        // 添加记录信息

        $conBalLog = array(
            'type' => 3,
            'pay_type' => 1,
            'param' => $orderId,
            'consumer_id' => $consumerId,
            'status' => 2,
            'amount' => $refund,
            'addtime' => time(),
            'confirm_time' => time()
        );
        //添加用户余额记录
        $cBLog = $this->mBuy->save($conBalLog);
        if (!$cBLog){
            return array('status' => 0, 'message' => '增加用户余额记录失败');
        }
        return array('status' => 1, 'message' => '成功');
    }
    /**
     * 售后退款
     * @param $info         array       售后订单详情
     * @param $refAmount    int         售后新的退款金额
     * @return array
     */
    public function _agreeRefund($info, $refAmount = 0){
        if (empty($info)){
            return array('status' => 0,'message' => '参数错误');
        }

        get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        get_instance()->loadModel('MerchantBalanceModel', 'mBalance', 'merchant');
        get_instance()->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
        get_instance()->loadModel('ConsumerBuyModel', 'mBuy', 'consumer'); // 资金账户模型
        get_instance()->loadModel('ConsumerPayModel', 'mPay', 'consumer'); // 用户支付模型

        $code = $info['code']; // 售后单号
        // 查看订单信息
        $orderInfo = $this->getInfo($info['order_id'], 0, 0, true);
        if (empty($orderInfo)){
            return array('status' => 0,'message' => '订单信息不存在');
        }
        if($orderInfo['status'] == 6){
            return array('status' => 0,'message' => '该订单已售后完成，请勿重复处理');
        }
        // 新填写的退款金额 -- 查看退款金额是否超出商品可退金额
        $refund = $info['refund_amount'];  // 退款金额

        if (($this->port == 'admin' || $this->port == 'county') && $refAmount){

            //最大退款金额
            $maxAmount = $orderInfo['reality_amount'];
            if ($refAmount > $maxAmount){
                return array('status' => 0,'message' => '退款金额不能大于'.$maxAmount.'元');
            }
            // 修改新退款金额
            $serRs = $this->mOrder->saveService(array('refund_amount' => $refAmount), $code);
            if (!$serRs){
                return array('status' => 0,'message' => '保存失败');
            }
            $refund = $refAmount;
        }
        // 添加记录信息
        $db = array(
            'type' => 3,
            'pay_type' => 1,
            'param' => $info['order_id'],
            'status' => 2,
            'addtime' => time(),
            'confirm_time' => time()
        );
        // 申请售后订单状态为待评价时才扣商家余额
        if ($info['order_status'] == 4) {

            $refundAmount = $orderInfo['merchant_income']; // 扣取商家金额
            if($refund < $orderInfo['reality_amount']){
                //如果退款金额小于实际用户支付金额 按比例扣除商家金额
                $refundAmount = sprintf('%.2f', ($refund/$orderInfo['reality_amount'])* $orderInfo['merchant_income']);
            }
            // 查看商家余额
            $merInfo = $this->mMerchant->getInfo($info['merchant_id'], 0, false);
            if (!$merInfo) {
                return array('status' => 0,'message' => '商家信息有误');
            }
            if ($refundAmount > $merInfo['balance']) {
                return array('status' => 0,'message' => '商家余额不足，不能退款');
            }
            // 减少商家余额
            $mer = $this->mMerchant->save(array('balance' => $merInfo['balance'] - $refundAmount), $info['merchant_id']);
            if (!$mer) {
                return array('status' => 0, 'message' => '扣除商家余额失败');
            }
            //添加商家扣款余额记录
            $merBalLog = $db;
            $merBalLog['merchant_id'] = $info['merchant_id'];
            $merBalLog['amount'] = -$refundAmount; // 扣款金额
            $merBalLog['percent'] = $orderInfo['percent'];

            $mBLog = $this->mBalance->save($merBalLog);
            if (!$mBLog){
                return array('status' => 0, 'message' => '保存商家余额记录失败');
            }
        }

        //添加用户余额记录
        $conBalLog = $db;
        $conBalLog['consumer_id'] = $info['consumer_id'];
        $conBalLog['amount'] = $refund;  // 退款金额

        if ($orderInfo['pay_type'] == 1){
            // 余额支付 -- 增加用户余额
            $con = $this->mConsumer->setConsumer($info['consumer_id'], $refund);
            if (!$con){
                return array('status' => 0, 'message' => '增加用户余额失败');
            }
        }else if ($orderInfo['pay_type'] == 2){
            // 微信支付退款到微信
            $db['pay_type'] = 2;
            if ($orderInfo['wx_type'] == 2){ // 微信公众号只退款
                $payTa = $this->mPay->WeChatRefund($orderInfo['pay_code'], $info['reality_amount'], $refund, $code);

            }else{ // APP微信退款
                $payTa = $this->mPay->wxRefund($orderInfo['pay_code'], $info['reality_amount'], $refund, $code);
            }
            if ($payTa['return_code'] == 'FAIL'){
                return array('status' => 0, 'message' => '退款失败，错误原因：'.$payTa['return_msg']);
            }
        }else if($orderInfo['pay_type'] == 3){
            // 支付宝支付退款到支付宝
            $db['pay_type'] = 3;
            $payTa = $this->mPay->zfbRefund($orderInfo['pay_code'], $refund, $code);
            if ($payTa != 10000){
                return array('status' => 0, 'message' => '退款失败');
            }
        }else{
            return array('status' => 0, 'message' => $orderInfo['pay_type'].'支付方式有误');
        }

        $cBLog = $this->mBuy->save($conBalLog);
        if (!$cBLog){
            return array('status' => 0, 'message' => '增加用户余额记录失败');
        }

        $re = $this->_orderServiceMessage($info, 1);
        if($re['status'] == 0){
            return array('status' => 0, 'message' => $re['message']);
        }
        return array('status' => 1, 'message' => '成功');
    }

    /**
     * 给用户发送售后消息
     * @param array         $info           售后订单详情
     * @param $type         int             1 同意       2 拒绝
     * @param $reason       string          拒绝原因
     */
    public function _orderServiceMessage($info, $type, $reason = ''){
        if ($type == 1){
            $title = '您的订单：'.$info['code'].'已同意退款';
            $content = '您的订单：'.$info['code'].'已同意退款';
        }else if($type == 2){
            $title = '您的订单：'.$info['code'].'已拒绝退款';
            $content = '拒绝原因：'.$reason;
        }else{
            return array('status' => 0, 'message' => '参数错误');
        }
        //推送消息
        $msgData = array(
            'title' => $title,
            'type' => 4,
            'consumer_id' => $info['consumer_id'],
            'content' => $content,
            'order_id' => $info['id'],
            'addtime' => time(),
        );

        get_instance()->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');

        if(!($this->mMessage->save($msgData))){
            return array('status' => 0, 'message' => '消息保存失败');
        }

        //删除消息查看记录
        //$this->mMessage->deleteView($info['merchant_id'], $msgInfo['id']);

        jpush($msgData['title'], $msgData['content'], 1, array($info['jpush_code']), 4, $info['id']);

        return array('status' => 1, 'message' => '消息发送成功');
    }

}